Let's say we have following if statement:
int a = 1;
int b = 2;
if(a < b) {
System.out.println("A is less than B!");
}
else {
System.out.println("A is greater or equal to B!");
}
I have been wondering that if ternary operator replaces if statement when if statement consists from one line of code in each sub-block (if and else blocks), then why above example is not possible to write like this with ternary operator?
(a < b) ? System.out.println("A is less than B!") : System.out.println("A is greater or equal to B!");
Let us write a program to find maximum of two numbers using ternary operator. If we compare syntax of ternary operator with above example, then − First, expression a > b is evaluated, which evaluates to Boolean false as value of variable 'a' is smaller than value of variable 'b'.
The ternary operator (? :) consists of three operands. It is used to evaluate Boolean expressions. The operator decides which value will be assigned to the variable. It is the only conditional operator that accepts three operands. It can be used instead of the if-else statement. It makes the code much more easy, readable, and shorter.
If we compare syntax of ternary operator with above example, then − First, expression a > b is evaluated, which evaluates to Boolean false as value of variable 'a' is smaller than value of variable 'b'. Hence value of variable 'b' i.e. '20' is returned which becomes final result and gets assigned to variable 'max'.
In C programming, we can also assign the expression of the ternary operator to a variable. For example, Here, if the test condition is true, expression1 will be assigned to the variable. Otherwise, expression2 will be assigned. In the above example, the test condition (operator == '+') will always be true.
You can only use ? :
for expressions, not statements. Try
System.out.println(a < b ? "A is less than B!" : "A is greater or equal to B!");
Note: this is also shorter/simpler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With