Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Very basic question about hidden if else How this works ??

 
Gemini Moses
Ranch Hand
Posts: 245
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
return map.get(Product1) != null ? (String) map.get(Product1) : NO;
 
Bridget Kennedy
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is an example of a ternary operator.

Here is another good description.
[ October 20, 2008: Message edited by: Bridget Kennedy ]
 
Ravikanth kolli
Ranch Hand
Posts: 179
Chrome Eclipse IDE Mac
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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;
 
Campbell Ritchie
Sheriff
Pie
Posts: 48940
60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).
  •  
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic