Enter your email address:

Delivered by FeedBurner


Tuesday, March 20, 2012

Java Conditional Operators

Java has the conditional operator. It's a ternary operator -- that is, it has three operands -- and it comes in two pieces, ? and :, that have to be used together. It takes the form

Boolean-expression ? expression-1 : expression-2
 

The JVM tests the value of Boolean-expression. If the value is true, it evaluates expression-1; otherwise, it evaluates expression-2. For
 

Example
if (a > b) {
     max = a;
}
else {
     max = b;
}


Setting a single variable to one of two states based on a single condition is such a common use of if-else that a shortcut has been devised for it, the conditional operator, ?:. Using the conditional operator you can rewrite the above example in a single line like this:

max = (a > b) ? a : b;

0 comments

Post a Comment