This week's book giveaway is in the Agile and other Processes forum. We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line! See this thread for details.
It is the same as the usual IF-ELSE statement. something like
if(condition) then do something 1 ; else do something 2
The tertiary operator is similar to..
(condition)? do something 1 : do something 2;
-kolli
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32675
4
posted
0
Originally posted by Ravikanth kolli: It is the same as the usual IF-ELSE statement.
No, it isn't. The ?: operator is an operator which has to fit inside a statement; if-else requires two statements. I liked Bridget Kennedy's first example (well, until I saw that lunatic Campbell Ritchie had replied), but am not quite so happy with the second.
boolean giveTicket; giveTicket = speed > speedLimit ? true : false; if (giveTicket) pullEmOver(); // nab the offender!
It should read
giveTicket = speed > speedLimit;
But they are right to point out the difference between ?: and if-else.
In Deitel and Deitel you find examples like this
. . . hour > 12 ? "pm" : "am" . . .
What you are doing is embedding a tiny choice between two possibilities inside a line. That example will return the String "am" or the String "pm" depending on the value of hour.
Notice the ?: operator takes 3 operands:
First: boolean value, Boolean, or expression returning a boolean.
Second: Any type, depending on what the rest of the statement needs.
Third: same as second (once any casts, implicit or explicit, are taken into consideration).