How do you use the ternary operator?

Byron Tymvios

The ternary operator or ?, is a shorthand if else statement. It can be used to evaluate an expression and return one of two operands depending on the result of the expression.

boolean b = true;
String s = ( b == true ? "True" : "False" );

This will set the value of the String s according to the value of the boolean b. This could be written using an if else statement like this:

boolean b = true;
String s;
if(b == true){
    s = "True";
}else{
    s = "False";
}

The ternary operator can be very usefull in reducing the number of lines of code as you can see, but beware it can make your code difficult to read and due to this is not ideal for nested statements. It can also be very usefull in testing for null values quickly.

0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact