Java program to find maximum of three numbers

Java 8Object Oriented ProgrammingProgramming

The maximum among three numbers can be found using an if else statement. A program that demonstrates this is given as follows.

Example

 Live Demo

public class Example {
   public static void main(String args[]) {
      int num1 = 15;
      int num2 = -5;
      int num3 = 7;
      if (num1 >= num2 && num1 >= num3)
         System.out.println( num1 + " is the maximum number.");
      else if (num2 >= num1 && num2 >= num3)
         System.out.println( num2 + " is the maximum number.");
      else
         System.out.println( num3 + " is the maximum number.");
   }
}

Output

15 is the maximum number.

Now let us understand the above program.

First, the three numbers are defined. If num1 is greater than num2 and num3, then it is the maximum number. If num2 is greater than num1 and num3, it is the maximum number. Otherwise, num3 is the maximum number. The code snippet that demonstrates this is given as follows.

int num1 = 15;
int num2 = -5;
int num3 = 7;
if (num1 >= num2 && num1 >= num3)
System.out.println( num1 + " is the maximum number.");
else if (num2 >= num1 && num2 >= num3)
System.out.println( num2 + " is the maximum number.");
else
System.out.println( num3 + " is the maximum number.");
raja
Published on 06-Dec-2018 07:15:24
Advertisements