# Find the Greatest of the Two Numbers in Java

Here, we will learn the basic java program to find the greatest of the two numbers.

## Problem :

simple example of problem :

#### Input :

```Enter the first number: 8
Enter the second number: 15```

#### Output :

`The greater number is: 15`

### Explanation:

In this example, the program compares the two numbers (8 and 15) and determines that 15 is greater, so it prints “The greater number is: 15”.

### Solution :

there are few ways to find the largest or greatest of two numbers in java:

• Method 1: Using if-else Statements
• Method 2: Using Ternary Operator
• Method 3: Using inbuilt math.max() method

### Approach 1 : Using if-else Statements

In this method we will use if-else statements to compare the two numbers  and print the greatest.

#### Algorithm

1. Start the program
3. Check if both the integers are equal, print “Equal” if true.
4. Check if number1>number2, print number1 if true.
5. Check if number2>number1, print number2 if true.
###### Code:
```// java program to find the largest of two numbers in java
public class Main
{
public static void main (String[]args)
{

int num1 = 70, num2 = 20;
if (num1 == num2)
System.out.println ("both are equal");
else if (num1 > num2)
System.out.println (num1 + " is greater");

else
System.out.println (num2 + " is greater");

}
}```
##### Output:
`70 is greater`

### Approach 2 : Using Ternary Operator:

In this method we’ll use the Ternary Operator and compare the two numbers to check for the greatest  or Largest among them.

#### Algorithm:

• Check for the greatest among the two using Ternary Operator.
```public class Main
{
public static void main (String[]args)
{
int num1 = 50, num2 = 30, temp;

if (num1 == num2)
System.out.println ("Both are Equal\n");
else
{
temp = num1 > num2 ? num1 : num2;
System.out.println (temp + " is largest");
}

}
}```
##### Output:

`50 is largest`

### Approach 2 : Using inbuilt max Function:

In this method we’ll use the inbuilt math.max() method to get the greatest or Largest of the two integer inputs

```public class Main {
public static void main(String args[])
{
int num1 = 13, num2 = 31;
if (num1 == num2)
System.out.println("both are equal");
else
// prints the maximum of two numbers
System.out.println(Math.max(num1, num2) + " is greater");
}
}
```

#### Output:

`31 is greater`

##### More java programs for practice:

Java Program to Reverse a Number

Java Program to Check a Number is Palindrome or Not

Java Program to Get Input from User

Addition of two numbers in java

Java Program to Check Leap Year