How To Use Conditional Expression ( ? : ) or Ternary Operator In JAVA?

Java_LOGO

Conditional Expression (operator)   is also known as the ternary operator. This operator consists of three operands and is used to evaluate Boolean Expressions. This is the only operator in Java with three operands.The operator is written as :

variable x = Boolean-expression ? expression-1 : expression-2

Semantics :
1.The JVM tests the value of Boolean-expression.
2. If  Boolean-expression's value is true, it evaluates expression-1.
3. Otherwise, it evaluates expression-2.

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

Above condition can be written using Conditional operator like this:
max = (a > b) ? a : b;

Example 2:
this.listModel=this.listModel==null?new ListModel():this.listModel;

1. The condition, (a > b), is tested.
2. If it is true the first value, a, is returned.
3. If it is false, the second value, b, is returned.
Share on Google Plus

About JK STACK

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment