In this tutorial you will learn about the Java Program to find largest of three numbers using ternary operator and its application with practical example.
In this tutorial, we will learn to create Java Program to find largest of three numbers using ternary operator using Java programming.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following Java programming topics:
- Java Operators.
- Basic Input and Output function in Java.
- Class and Object in Java.
- Basic Java programming.
- If-else statements in Java.
- For loop in Java.
Ternary Operator Syntax :
The use of a ternary operator in our program decreases the number of lines of code and increases performance .
Syntax of ternary Operator.
variable = condition ? expression1 : expression2 ;
Java Program to find largest of three numbers using ternary operator
In this program we would find largest of three numbers using ternary operator . First of we would take three values from user and find the find largest of three numbers using ternary operator. Let’s have a look at the code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// java program to find greates among three import java.util.Scanner; public class Largest { public static void main(String[] args) { // Declaring variables and taking values from user.. int n1, n2, n3, grt; Scanner s = new Scanner(System.in); System.out.println("Enter three numbers "); n1 = s.nextInt(); n2 = s.nextInt(); n3 = s.nextInt(); // Calculating greatest ampng three.. grt = n3 > (n1 > n2 ? n1 : n2) ? n3 : ((n1 > n2) ? n1 : n2); // printing the result.. System.out.println("Largest Number:"+grt); } } |
Output
Greatest among three.
In the above program, we have first declared and initialized a set variables required in the program.
- n1,n2 and n3 = it will hold entered numbers.
- grt= it will hold result in it
After that we take a numbers from user and find greatest among three using ternary operator.
after taking values from users we use ternary operator to calculate greatest among three
Boolean result= Condition ? true value : false value; it returns the Boolean value(true/false).
Logic behind the above expression is explained.
And finally we will print the result as shown in above image.