Home » Java Program to Find Largest of Three Numbers

Java Program to Find Largest of Three Numbers

by Online Tutorials Library

Java Program to Find Largest of Three Numbers

In this section, we will learn how to create a Java program to find the largest of three numbers. Along with this, we will also learn to find the largest of three numbers in Java using the ternary operator.

Using Ternary Operator

Before moving to the program, let’s understand the ternary operator.

It is a part of the Java conditional statement. It contains three operands. It evaluates a Boolean expression and assigned a value based on the result. We can use it in place of the if-else statement. The syntax of the ternary operator is as follows:

If the above expression returns true the value before the colon is assigned to the variable variable_name, else the value after the colon is assigned to the variable.

Let’s use the ternary operator in a Java program to compare three variables.

In the following program, we have used two ternary operators to compare three numbers.

LargestNumberExample1.java

Output:

Enter the first number:  23  Enter the second number:  11  Enter the third number:  67  Largest Number is: 67  

We can also compare all the three numbers by using the ternary operator in a single statement. If we want to compare three numbers in a single statement, we must use the following statement.

In the following program, we have used a single statement to find the largest of three numbers.

LargestNumberExample2.java

Output:

Enter the first number:  45  Enter the second number:  87  Enter the third number:  34  The largest number is: 87  

Using if-else..if

LargestNumberExample3.java

Output:

78 is the largest number  

Using nested if

LargestNumberExample4.java

Output:

The largest number is: 1010  

LargestNumberExample5.java

Output 1:

Enter three integers:   12 110 9  The largest number is: 110  

Output 2:

Enter three integers:   9 9 9  The numbers are same.  

Next TopicJava Programs

You may also like