Write a program to find the Maximum of Two Numbers using switch statement


This Java program takes two integers as input and finds the maximum of the two. The program uses a ternary operator to check whether the first number is greater than the second number. If it is, the value of the variable res is set to 1. Otherwise, it is set to 0.

If the first number is not greater than the second number, the program checks whether the two numbers are equal. If they are equal, the program prints "Both are Equals". If they are not equal, the program prints "Maximum Number is" followed by the second number.

If the first number is greater than the second number, the program simply prints "Maximum Number is" followed by the first number. Here's how the program works:

  • The program prompts the user to enter two integers using System.out.printf() and Scanner.nextInt() method, which are stored in the variables n1 and n2.
  • The program uses a ternary operator to check whether n1 is greater than n2. If it is, the value of the variable res is set to 1. Otherwise, it is set to 0.
  • If res is 0, the program checks whether n1 is equal to n2. If it is, the program prints "Both are Equals". If it is not, the program prints "Maximum Number is" followed by the second number n2.
  • If res is 1, the program simply prints "Maximum Number is" followed by the first number n1.

Source Code

import java.util.Scanner;
public class MaxNum
{
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);
		System.out.printf("Enter the Number 1 : ");
		int n1 = input.nextInt();
		System.out.printf("Enter the Number 2 : ");
		int n2 = input.nextInt();
		int res = n1>n2?1:0;
		switch (res)
		{
			case 0:				
				res = n1==n2?1:0;
				switch(res)
				{
					case 0:						
						System.out.printf("Maximum Number is "+n2);
						break;					
					case 1:						
						System.out.printf("Both are Equals");
						break;
				}
				break;
 
			case 1:
				System.out.printf("Maximum Number is "+n1);
				break;
		}
	}
}

Output

Enter the Number 1 : 68
Enter the Number 2 : 53
Maximum Number is 6