Have a question?
Message sent Close
View Categories

What is Ternary Operators in Java?

What is Ternary Operators in Java?

📄
filename.js
public class TernaryOperatorExample {

    public static void main(String[] args) {

        int a = 10;

        int b = 20;

        // Using ternary operator to find the larger number

        int max = (a > b) ? a : b;

        System.out.println("The larger number is " + max);

    }

}

Output:
The larger number is 20

📄
filename.js
public class TernaryOperatorExample {

    public static void main(String[] args) {

        int score = 85;

        // Using ternary operator to assign a grade

        String grade = (score >= 90) ? "A" :

                       (score >= 80) ? "B" :

                       (score >= 70) ? "C" :

                       (score >= 60) ? "D" : "F";

        System.out.println("The grade is " + grade);

    }

}

Output:
The grade is B