File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Very basic question about hidden if else How this works ?? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Very basic question about hidden if else How this works ??" Watch "Very basic question about hidden if else How this works ??" New topic
Author

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

Gemini Moses
Ranch Hand

Joined: Jan 04, 2001
Posts: 245
return map.get(Product1) != null ? (String) map.get(Product1) : NO;
Bridget Kennedy
Ranch Hand

Joined: Nov 30, 2004
Posts: 84
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

Joined: Feb 10, 2008
Posts: 179

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: 39784
    
  28
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).
  •  
    I agree. Here's the link: http://aspose.com/file-tools
     
    subject: Very basic question about hidden if else How this works ??