A tiny if/else
When you just need to pick one of two values, the ternary operator fits it in one line:
condition ? valueIfTrue : valueIfFalse
public class Main {
public static void main(String[] args) {
int number = 7;
String kind = (number % 2 == 0) ? "even" : "odd";
System.out.println(number + " is " + kind);
int a = 12, b = 30;
int bigger = (a > b) ? a : b;
System.out.println("Bigger: " + bigger);
}
}Output
7 is odd Bigger: 30
Read it as: “Is the number even? If yes, "even", otherwise "odd".”
Tip: Use
? :only for short, simple choices. For anything bigger, a normalif/elseis easier to read.