Finding the maximum of 2 values

 

As another example to illustrate the use of methods, let’s suppose we’d like to write a program that determines which of two user-entered values is largest.  The main method will take care of prompting the user for values, and we’ll have a method called max, which returns the largest of 2 integers that are passed as arguments.  To determine the largest, max compares the parameters and returns the right variable according to the result of the comparison.

 

      public class MoreMethods

      {

            public static void main(String[] args)

            {

                  Scanner input = new Scanner(System.in);

 

                  // obtain two values – missing an output statement

                  int num1 = input.nextInt();

                  int num2 = input.nextInt();

 

                  // invoke max and save result in ‘largest’

                  int largest = max(num1, num2);

                  System.out.println(largest + “ is the maximum.”);

            }

 

            public static int max(int a, int b)

            {

                  if (a > b)

                        return a;

                  else

                        return b;

            }

      }