Java ?: operator

One of the least understood, and most underestimated Java language constructs is the ?: operator. Most people never even seen it in action. And those who did, never actually used it to do anything meaningful. Imagine something like this:

public generateFoo(int threshold)
{
    if(threshold > MIN_THRESHOLD)
       return new Foo();
    else
       return null;
}

In this snippet of code we have a function which generates a new Foo object if the passed argument is greater than some minimal threshold. If it is below threshold we return null. This is not an uncommon scenario… But with the ?: operator we could accomplish all of this on a single line.

public generateFoo(in threshold)
{
    return (threshold > MIN_THRESHOLD) ? new Foo() : null;
}

If you didn’t catch that let me show you something simpler:

int foo = bar ? a : b;

Java expects to a boolean or an expression evaluating to a boolean before the question mark. If that expression is true, then the whole statement evaluates to a. Else it evaluates to b.

It is elegant, produces a lean code and saves you one return statement. It is a good coding practice to have one return statement per method when possible. I think more Java programmers should embrace this little syntactic sugar. It saves you allot of typing when used appropriately.

This entry was posted in Uncategorized and tagged . Bookmark the permalink.



16 Responses to Java ?: operator

  1. ellioman ICELAND Mozilla Firefox Mac OS says:

    Thanks for this!
    I needed a good explanation, and you gave me one ;)

    Cheers from Iceland.

    Reply  |  Quote
  2. Patrick CANADA Mozilla Firefox Linux says:

    public Playlist(Playlist playList){
    if (playList != null){
    for(int i = 0; i

    Reply  |  Quote
  3. Luke Maciak UNITED STATES Mozilla Firefox Ubuntu Linux Terminalist says:

    Patrick – I think your comment got eaten. Remember, you can’t use the < and > unless you put them in the <pre> tag. Click the code button above the textbox. Observe:

    inside here I can use <> as normal

    Alternatively you can use the &lt; and &gt; HTML entities like I did above.

    Also, preview button does wonders for you. ;)

    Reply  |  Quote
  4. Patrick CANADA Mozilla Firefox Linux says:

    thx, I’ll repost.

    Reply  |  Quote
  5. Patrick CANADA Mozilla Firefox Linux says:

    Well I used something like

    (boolean)? System.out.println(“Some text”):System.out.println(“Some other text”);

    Putting it in an if statement works no problem.

    Reply  |  Quote
  6. Patrick CANADA Mozilla Firefox Linux says:

    But with the question mark operator, it did not work.

    Reply  |  Quote
  7. Luke Maciak UNITED STATES Mozilla Firefox Ubuntu Linux Terminalist says:

    Well, that is the one way you are not supposed to use the question mark statement. This statement is supposed to evaluate the boolean, and based on it’s value return the result of the statement to the left or the right of the colon.

    In other words, the two statements are required to return a value. Since println() is void, I believe this syntax will throw error. So you are right, in your example, the if statement is definitely the correct approach.

    To put it more simply, the question mark statement must evaluate to (or return) a value of some sort. It is not supposed to be used to perform an action.

    I hope that makes sense. :)

    Reply  |  Quote
  8. Patrick CANADA Mozilla Firefox Linux says:

    Ya thanks, it make sense.

    Reply  |  Quote
  9. test POLAND Internet Explorer Windows says:

    another advantage that it will not excute statement1:statement2 only the correct one

    Reply  |  Quote
  10. wanacas ESTONIA Mozilla Firefox Windows says:

    This works:
    System.out.println(boolean ? “Some text” : “Some other text”);

    Reply  |  Quote
  11. span AUSTRALIA Mozilla Firefox Windows says:

    Thanks for the clear explanation :)

    Reply  |  Quote
  12. Marcel NETHERLANDS Mozilla Firefox Windows says:

    Thanks, I understand this!

    Reply  |  Quote
  13. Guido NETHERLANDS Mozilla Firefox Ubuntu Linux says:

    Nice explanation, thanks.

    Reply  |  Quote
  14. D AUSTRALIA Opera Windows says:

    Returning null makes Baby Jesus cry.

    Reply  |  Quote
  15. Francis BELGIUM Mozilla Firefox Windows says:

    Thanks, you turned Chinese into something understandable ;-)

    Reply  |  Quote
  16. suvi SWITZERLAND Mozilla Firefox Windows says:

    instead of
    int foo = bar ? a : b;
    this
    var== expression ? a: b;

    Reply  |  Quote

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>