Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
The moose likes Beginning Java and the fly likes What does ?false:true do/mean? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Building Microservices this week in the Design forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "What does ?false:true do/mean?" Watch "What does ?false:true do/mean?" New topic
Author

What does ?false:true do/mean?

Angelo Tan
Greenhorn

Joined: Oct 29, 2010
Posts: 10

I've encountered this piece of code many times already. I'm wondering what is it for? What does it do? And when should i use it?
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 4001
    
  18

Never, because they are pretty useless.

This is called the ternary operator. It consists of a boolean expression, followed by ?, followed by an expression, followed by :, and finally another expression.

If the boolean expression before the question mark evaluates to true, the operator returns the expression after the question mark. Otherwise, it returns the expression after the colon.
Here is an example:
This piece of code assigns to max either a or b, whichever is larger. The ternary operator has its uses. The reason your examples shouldn't be used, is because they simply return the outcome of the boolean expression before the question mark, or its inverse.


The mind is a strange and wonderful thing. I'm not sure that it will ever be able to figure itself out, everything else, maybe. From the atom to the universe, everything, except itself.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14961
    
  26

A line like this:

means exactly the same as this:

It's just a shorter syntax to write.

As Stephan noted, using "true" and "false" (or "false" and "true") for a and b is pretty useless...


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Angelo Tan
Greenhorn

Joined: Oct 29, 2010
Posts: 10
thanks for the clear and thorough explanation.

got it now.
 
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com
 
subject: What does ?false:true do/mean?
 
It's not a secret anymore!