if-else
statement.
condition ? value1 : value2;
if-else
: Instead of writing an entire if-else block, the ternary operator allows you to decide between two values in one line.
public class TernaryOperator
{
public static void main(String[] args)
{
int a = 10, b = 20;
// Using ternary operator to find the maximum of two numbers
int max = (a > b) ? a : b;
System.out.println("The maximum value is: " + max); // Output: The maximum value is: 20
// Using ternary operator to check if a number is even or odd
String result = (a % 2 == 0) ? "Even" : "Odd";
System.out.println("The number is: " + result); // Output: The number is: Even
// Nested ternary operator
int largest = (a > b) ? ((a > 15) ? a : 15) : ((b > 15) ? b : 15);
System.out.println("The largest value is: " + largest); // Output: The largest value is: 20
}
}
The maximum value is: 20 The number is: Even The largest value is: 20
int max = (a > b) ? a : b;
String result = (a % 2 == 0) ? "Even" : "Odd";
int largest = (a > b) ? ((a > 15) ? a : 15) : ((b > 15) ? b : 15);
int result = (score > 50) ? 1 : 0;
return (age >= 18) ? "Adult" : "Minor";
if-else
statements.
if-else
blocks.
if
or else
block).
int max = (a > b) ? a : b;
.
value1
and value2
in the ternary operator must be of the same type or must be compatible types.
int
and another as a String
unless there’s an explicit type cast.
int largest = (a > b) ? ((a > 15) ? a : 15) : ((b > 15) ? b : 15);
.
value2
) is only evaluated if the condition is false
.
&&
and ||
operators.
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
We’re here to make our tutorials better based on your thoughts and suggestions.