Returning a Value from a Method

5.5 Returning a Value from a Method

To let a method return a value, use the return statement. Here is an example of value retuning method that takes one parameters num and returns the factorial of num.
import java.util.Scanner;    // Needed for the Scanner class

/*
* This program demonstrate a
* value returning method.
*/
public class ReturnMethod
{
   public static void main(String[] args)
   {
      // Create a Scanner object for keyboard input.
      Scanner console = new Scanner(System.in);
      int     number,    // to hold the number
              x;         // to hold the factorial

      // Get the number.
      System.out.print("Enter number : ");
      number = console.nextInt();

      // Call factorial method and return result to x.
      x = factorial(number);

      // Display the factorial.
      System.out.println("Factorial : " + x);
   }

   /**
    *  The factorial method accept a number
    *  and returns the factorial.
    */
   public static int factorial(int num)
   {
      int fact = 1;

      for (int i = 1; i <= num; i++)
      {
         fact = fact * i;
      }

      return fact;
   }
}
Output :
Enter number : 4
Factorial : 24

No comments:

Post a Comment

Pages