0
0
Javaprogramming~5 mins

Ternary operator in Java

Choose your learning style9 modes available
Introduction

The ternary operator lets you choose between two values quickly based on a condition. It makes simple decisions easier and your code shorter.

When you want to assign a value based on a quick yes/no question.
When you want to print different messages depending on a condition.
When you want to return one of two values from a method without writing if-else.
When you want to simplify simple if-else statements into one line.
Syntax
Java
result = condition ? valueIfTrue : valueIfFalse;

The condition is a boolean expression that is either true or false.

If condition is true, valueIfTrue is used; otherwise, valueIfFalse is used.

Examples
Assigns the bigger of a or b to max.
Java
int max = (a > b) ? a : b;
Stores "Pass" if score is 50 or more, otherwise "Fail".
Java
String result = (score >= 50) ? "Pass" : "Fail";
Prints a message depending on whether it is sunny or not.
Java
System.out.println(isSunny ? "Take sunglasses" : "Take umbrella");
Sample Program

This program checks if someone is old enough to vote. It uses the ternary operator to set "Yes" or "No" based on the age.

Java
public class TernaryExample {
    public static void main(String[] args) {
        int age = 18;
        String canVote = (age >= 18) ? "Yes" : "No";
        System.out.println("Can vote? " + canVote);
    }
}
OutputSuccess
Important Notes

The ternary operator is best for simple decisions. For complex logic, use if-else for clarity.

Both valueIfTrue and valueIfFalse should be of compatible types.

Summary

The ternary operator is a short way to choose between two values based on a condition.

It uses the syntax: condition ? valueIfTrue : valueIfFalse.

Use it to make your code shorter and easier to read for simple decisions.