I'm studying some Java at the moment at I've come across the following piece of code. I understand how the typical ternary operator (e.g. the line beginning with "boolean a" below), but I can't understand how to read the expression on the line beginning with "boolean b". Any help on how to read this line would be much appreciated! Thanks!
public class Ternary{
public static void main (String[] args){
int x = 10;
int i = 2;
boolean a = x > 10 ? true: false;
boolean b = a = true ? ++i > 2 ? true:false:false;
System.out.print(b);
}
}
Break it up like this:
true ? (++i > 2 ? true
: false)
: false;
So here the testing condition is always set to true
. So the branch of the ternary that executes is the ++i > 2 ? true : false
part.
This simply checks to see if after incrementing, i
is greater than 2
. If so, it will return true
. Otherwise it will return false
.
This whole expression is actually needlessly complex. It can simply be written as such:
boolean b = a = (++ i > 2);
However, the code is probably logically incorrect since this abstruse expression doesn't make that much sense. Since the previous line sets the value of a
, I'm assuming that the next line actually intends to test a
. So the actual intent might be:
boolean b = a == true ? ++i > 2 ? true : false : false; //notice the ==
In which case you can break it up as:
(a == true) ? (++i > 2 ? true
: false)
: false;
But you don't need to actually do a == true
since a
is already a boolean
, so you can do:
a ? (++i > 2 ? true
: false)
: false;
Here, it checks to see if a
is true
. If it is, it performs the check we already went over (i.e., to see if the incremented value of i
is greater than 2
), otherwise it returns false
.
But even this complicated expression can be simplified to just:
boolean b = a && (++i > 2);
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