Java ternary operator
Created By: chatGPT
Java provides a shorthand way to evaluate conditions and assign a value using the ternary operator. It is a concise way to represent an
if-else
statement. The syntax of the ternary operator is: condition ? valueIfTrue : valueIfFalse
. If the condition
evaluates to true
, valueIfTrue
is returned; otherwise, valueIfFalse
is returned.int a = 10;
int b = 20;
int max = (a > b) ? a : b;
System.out.println(max); // Output: 20
You can use the ternary operator for more complex expressions as well. It’s handy when you want to avoid multiple lines of code for simple conditional assignments.
String result = (a < b) ? "a is less than b" : "a is not less than b";
System.out.println(result);
// Output: a is less than b
If you have nested conditions, you can place a ternary operator inside another ternary operator, though it can decrease code readability.
int score = 85;
String grade = (score >= 90) ? "A" : (score >= 80) ? "B" : "C";
System.out.println(grade); // Output: B
Remember that while the ternary operator is useful, it’s best used for simple assignments. For complex logic, traditional
if-else
statements are often more readable.if (score >= 90) {
System.out.println("A");
} else if (score >= 80) {
System.out.println("B");
} else {
System.out.println("C");
}