In this tutorial, you will learn how to write Java Program to print the maximum or largest number among two numbers. There are various approach to solve and write the program. But in this tutorial we will write program using while loop.
Our Problem Statement
Here we have given the two integer input number ‘a’ and ‘b’. Then after the execution of the program our output should be a or b which will be greater.
Example:
Suppose two input numbers given by user is 23 and 45
then output should be 45
As 45 is the greatest / maximum among 23 and 45.
There are multiple logics and algorithms to write the program for finding largest among two numbers. In this complete tutorial post we will see three ways
Here are the list of ways used to do the job:
- Find largest/maximum using if…else
- Find largest/maximum using Math.max()
- Find largest/maximum using user-defined function
Our Logic
- Taking two integer inputs from the users using Scanner.
- Using if else statement our condition is, first check num1 > num2, if correct then print num1.
- If above condition failed then call else block and print num2.
Program 1 : Java program to print largest/maximum using if…else
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
int num1, num2, largest;
Scanner scan = new Scanner(System.in);
System.out.print("Enter the First Number: ");
num1 = scan.nextInt();
System.out.print("Enter the Second Number: ");
num2 = scan.nextInt();
if(num1>num2)
largest = num1;
else
largest = num2;
System.out.println("\nLargest number among two = " +largest);
}
}
Output
Enter the First Number: 43
Enter the Second Number: 22
Largest number among two = 43
Program 2 : Find largest/maximum using Math.max()
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
int num1, num2, largest;
Scanner scan = new Scanner(System.in);
System.out.print("Enter the First Number: ");
num1 = scan.nextInt();
System.out.print("Enter the Second Number: ");
num2 = scan.nextInt();
System.out.println("\nLargest number among two = " +Math.max(num1, num2));
}
}
Output
Enter the First Number: 23
Enter the Second Number: 34
Largest number among two = 34
Program 3 : Find largest/maximum using user-defined function
import java.util.Scanner;
public class Main
{
public static int LargestAmongTwo(int num1, int num2)
{
return (num1>num2) ? num1:num2;
}
public static void main(String[] args)
{
int num1, num2, largest;
Scanner scan = new Scanner(System.in);
System.out.print("Enter the First Number: ");
num1 = scan.nextInt();
System.out.print("Enter the Second Number: ");
num2 = scan.nextInt();
System.out.println("\nLargest number among two = " + LargestAmongTwo(num1, num2));
}
}
Output
Enter the First Number: 54
Enter the Second Number: 23
Largest number among two = 54