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).
subject: Very basic question about hidden if else How this works ??