The Ternary Operator


Lesson 5 introduced the if statement. Often you want to assign a value to a variable or return a value from a method based on the results of an if conditional. For example:

 String message =    "the course has " + getText(sessions) + " sessions"; ... private String getText(int sessions) {    if (sessions == 1)       return "one";    return "many"; } 

For simple conditional expressions that must return a new value, Java provides a shortcut form known as the ternary operator. The ternary operator compacts the if-else statement into a single expression. The general form of the ternary operator is:

 conditional ? true-value : false-value 

If conditional returns the value TRue, the result of the entire expression is TRue-value. Otherwise the result of the entire expression is false-value. Using the ternary operator, you can rewrite the previous code to produce a message as:

 String message =    "the course has " + (sessions == 1 ? "one" : "many") + " sessions"; 

If the value of sessions is 1, the parenthesized ternary expression returns the String "one", otherwise it returns "many". This result string is then used as part of the larger string concatenation.

The ternary operator is a holdover from the language C. Do not use the ternary operator as a general replacement for the if statement! The best use of the ternary operator is for simple, single-line expressions like the one shown here. If you have more complex needs, or if the code won't fit on a single line, you're better off using an if statement. Abuse of the ternary operator can result in cryptic code that is more costly to maintain.



Agile Java. Crafting Code with Test-Driven Development
Agile Javaв„ў: Crafting Code with Test-Driven Development
ISBN: 0131482394
EAN: 2147483647
Year: 2003
Pages: 391
Authors: Jeff Langr

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