Java Online Compiler
Example: Greatest of Two Numbers using Ternary Operator in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Greatest of Two Numbers using Ternary Operator import java.util.Scanner; // Main class containing the entry point of the program public class Main { public static void main(String[] args) { // Step 1: Create a Scanner object to read user input Scanner scanner = new Scanner(System.in); // Step 2: Prompt the user to enter the first number System.out.print("Enter the first number: "); int num1 = scanner.nextInt(); // Step 3: Prompt the user to enter the second number System.out.print("Enter the second number: "); int num2 = scanner.nextInt(); // Step 4: Use the ternary operator to find the greatest number int greatest = (num1 > num2) ? num1 : num2; // Step 5: Print the greatest number System.out.println(greatest + " is the greatest number."); // Step 6: Close the scanner scanner.close(); } }
Output
Clear
ADVERTISEMENTS