In this program, we will learn to code the Java Program to Find Largest of Three Numbers using Ternary Operator. Let’s understand How ternary operators work in Java Programming Language. In previous programs, we have learned to code the Java Program to Find Largest of Three Numbers.
Let’s see the code of the Java Program to Find Largest of Three Numbers using Ternary Operator.
Java Program to Find Largest of Three Numbers using Ternary Operator
import java.util.*; public class Main { public static void main(String arr[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter three numbers: "); int one = sc.nextInt(); int two = sc.nextInt(); int three = sc.nextInt(); int largest = (one > two)&&(one > three) ? one : (two > three) ? two : three; System.out.println("Largest of the three is "+largest); } }
Output
Enter three numbers: 111 51 777
Largest of the three is 777
How Does This Program Work ?
Scanner sc = new Scanner(System.in); System.out.println("Enter three numbers: "); int one = sc.nextInt(); int two = sc.nextInt(); int three = sc.nextInt();
In this program, we are taking the input of three numbers using the Scanner Class to take input in Java.
int largest = (one > two)&&(one > three) ? one : (two > three) ? two : three;
then, using the ternary operator i.e. (condition ? ans1 : ans2)
we compare the given three numbers and find out the largest of the three.
System.out.println("Largest of the three is "+largest);
Then, we display the result using the System.out.println()
function.
This is the Java Program to Find Largest of Three Numbers using Ternary Operator.
Conclusion
I hope after going through this post, you understand Java Program to Find Largest of Three Numbers using Ternary Operator. We discussed two approaches in this post.
If you have any doubt regarding the topic, feel free to contact us in the Comment Section. We will be delighted to help you.
Also Read: