1. Computing & Technology

Discuss in my forum

The ternary operator "?:" earns its name because it's the only operator to take three operands. It is a conditional operator that provides a shorter syntax for the if..then..else statement. The first operand is a boolean expression; if the expression is true then the value of the second operand is returned otherwise the value of the third operand is returned:

boolean expression ? value1 : value2

For example, the following if..then..else statement

boolean isHappy = true;
String mood = "";
if (isHappy == true)
{
  mood = "I'm Happy!";
}
else
{
  mood = "I'm Sad!";
}

can be reduced to one line using the ternary operator:

boolean isHappy = true;
String mood = (isHappy == true)?"I'm Happy!":"I'm Sad!";

Generally the code is easier to read when the if..then..else statement is written in full but sometimes the ternary operator can be a handy syntax shortcut.

Comments
July 1, 2009 at 1:29 pm
(1) ax says:

that one line should be more concise:

String mood = isHappy ? “I’m Happy!” : “I’m Sad!”;

you don’t have to compare a boolean with true or false, as evaluating it as an expression yields true or false already.

July 1, 2009 at 6:42 pm
(2) Paul Leahy says:

Yep, you’re right. And, if you look at the condition in the if statement, that too can be reduced to being just

if (isHappy)

I think having the expressions written so that beginners can see how the logic is being evaluated can make them a little easier to understand. But, I’ll add a note to the end of the glossary entry with the concise version too.

September 17, 2010 at 11:09 am
(3) вавыфавыфа says:

until you need to debug that sht

August 23, 2011 at 9:44 pm
(4) Roark says:

Debugging it is not so difficult if you do understand it. Making things clear is important but being concise does produce faster and better code.

November 6, 2011 at 5:07 am
(5) Frank says:

Roark, more concise code does not run any faster. You’re writing in a high level language like Java so your code will be readable. The byte-compiled if/else and ternary will ultimately run the same, no matter how many ‘lines of code’ you use.

February 14, 2012 at 9:43 am
(6) Didar says:

Great explanation….thanks a lot

Leave a Comment

Line and paragraph breaks are automatic. Some HTML allowed: <a href="" title="">, <b>, <i>, <strike>

©2012 About.com. All rights reserved.

A part of The New York Times Company.