Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What does ?false:true do/mean?

 
Angelo Tan
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Pie
Posts: 6106
72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Pie
Posts: 15438
41
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...
 
Angelo Tan
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks for the clear and thorough explanation.

got it now.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic