Search code examples
javabooleanboolean-operations

The ? boolean zen operator


I've never used the ? operator before and I'm trying to figure out how it works.

I have been reading countless pages and decided to try for myself.

I have the following statement:

 getSelection().equalsIgnoreCase("Måned") ? calendarView.currentlyViewing.set(Calendar.Year) : showPopup();

As far as I can understand, if the left hand side (boolean) is true it will set my calendarView.to year and if not (getSelection is not equal to måned) it will call the method showPopup().

But when I type this into Eclipse I get a syntax error.

What am I doing wrong?


Solution

  • You're trying to use the conditional ? : operator to decide which statement to execute. That's not its intention. The conditional operator can't be used as a statement - it's only to choose which expression to use as the overall result.

    So this is fine:

    foo(condition ? nonVoidMethod1() : nonVoidMethod2());
    

    but this isn't:

    condition ? voidMethod1() : voidMethod2();
    

    You should just use an if statement here:

    if (getSelection().equalsIgnoreCase("Måned")) {
        calendarView.currentlyViewing.set(Calendar.Year);
    } else {
        showPopup();
    }