Ternary Operator

     

This operator is a shorthand version of the if/else construct that some developers find confusing, and others like. It takes the following form:

 

 boolean expression ? action if true : action if false 

The first part is an expression that evaluates to either true or false . The code after the question mark executes if the expression is true; the code after the colon executes only if the expression is false.

It serves as a replacement shorthand for the following construct:

 

 if (boolean expression) {    action if true; } else {    action if false; } 

So it looks like this in code:

 

 public int returnLesserOfTwo(int x, int y) {    return (x < y ? x : y); } 

If you pass that method an x value of -20 and a y value of -80, it returns -80. I like it. Just don't nest them if you want to eschew obfuscation. Here's what I mean. Three nested ternary operators just isn't pretty.

 

 private static boolean badTernaryNest() {    return (6%3>1)?(5>10?(2<=3):(3*4<10?4>3:7==7)):false; } 

Although you can do that (it returns false if you're interested), please don't. It is almost guaranteed to incur the wrath of anyone who has to read your code.



Java Garage
Java Garage
ISBN: 0321246233
EAN: 2147483647
Year: 2006
Pages: 228
Authors: Eben Hewitt

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net