This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
The ternary operator is <evaluation> ? <true result> : <false result>.
Your code shows three ternary operators. Ugly but valid.
What it is you don't understand? This seems simple enough. Just not that the condition is no "b==!b" but "b=!b", which means the result of "!b" will be assigned to "b" and then that value used in the evaluation.
So in the first "b=!b", the evaluation is "true".
To add to what Jason said: b=!b is assigning the value of !b(which is true) to b, now b becomes true. After the first ternary there is nothing to do there and second ternary will assign the value of !b to b, keep in mind that b is true from the first ternary and now in the second b will become false. So when executing the second ternary it will print hello with lower initial letter h because b is false.
Joined: Jun 09, 2009
This question highlights one of the issues with ternary operators. Whilst they may be convenient, when you nest them or they go wrong; they can be a royal pain.
On the job I stick to fully declared if/else with braces; unless I have good reason not to.
Balraj Momi wrote:Sorry to bother you guys again I could understand first half of it.
This is how I could interpret half first half of this condition
In this particular case, it is far to convoluted to use a ternary operator as you have nested statements. Here the use of the ternary is making things far to complicated.
One design recommendation in Java is to factor bigger complex tasks out into smaller easier ones. The ability to do this due to the scope and
flexibility of the Java language is one of its defining factors as one of the best languages out there (although some may argue the opposite).
SO in this case, it would be far better to re-factor the code to use the usual if-else. Of course you could do this anyway to understand it more, yet still
keep your final code as ternary. For me however, the easier the better!
See Anastasia's code post above, it really makes things simpler don't you think?
be a well encapsulated person, don't expose your privates, unless you public void getWife()!