I have a piece of code like follows
public class Test{
public static void main(String[] args) {
System.out.println(true?false:true == true?false:true);
-----------------------
}
}
The output is false. If you are using Eclipse you get a wavy (dashed here) line and warning like “Comparing identical expressions”. Note the start of the wavy line.
I changed the code to the following
public class Test{
public static void main(String[] args) {
System.out.println((true?false:true) == (true?false:true));
---------------------------------------
}
}
The output is true. If you are using Eclipse you get a wavy (dashed here) line and warning like “Comparing identical expressions”. Note the start of the wavy line now.
Why the difference?
In case your problem is the difference of outcomes, this is because of the order of precedence of the operators you use. Check here for details. According to that order of precedence:
is the same as this:
so it will always evaluate to false. You could put anything after the colon since it’s never evaluated anyway (if I remember correctly and the ternary operator uses lazy evaluation); the reason for this is that
always evaluates to A.
On the other hand,
will have both sides of the comparison operator == evaluate to false, so
which is a true statement.
So the difference here is the order in which the operators are evaluated, which is determined by the parentheses you use and, if there is ambiguity that isn’t resolved by parentheses, by the order of precedence of the operators that are used.
In general, the ternary operator “? :” works like this
If A is true, evaluate to B, else evaluate to C. A has to be a boolean expression, B and C can be whatever you want; you’ll have to deal with type mismatches though if you want to assign the evaluated value to a variable and they are of different types.