Marcin Knapik
Marcin Knapik

Reputation: 35

Java "short" if with multiple "?"

How something like this works:

System.out.println(x>20 ? x<0 ? 10:8:7);

Or more complicated like:

System.out.println(x>20 ? x<10 ? x<2? x==0? 10:8:7:5:8);

I understand default usage like this:

 System.out.println(z>2?10:8);

But "longer" version gives me score that I don't understand why.

Upvotes: 0

Views: 89

Answers (1)

Idle_Mind
Idle_Mind

Reputation: 39142

You can think of this:

x>20 ? x<0 ? 10 : 8 : 7

As:

x>20 ? (x<0 ? 10 : 8) : 7

You start with the inner most ? and : pair, group them together, and repeat while working your way outwards.

Written verbosely, it would look like this instead:

if (x>20) {
    if (x<0) {
        return 10;
    }
    else {
        return 8;
    }    
}
else {
    return 7;
}

Here's the longer one:

x>20 ? x<10 ? x<2 ? x==0 ? 10 : 8 : 7 : 5 : 8

with grouping:

x>20 ? (x<10 ? (x<2 ? (x==0 ? 10 : 8) : 7) : 5) : 8

and written verbosely:

if (x>20) {
    if (x<10) {
        if (x<2) {
            if (x==2) {
                return 10;
            }
            else {
                return 8;
            }
        }
        else {
            return 7;
        }
    }
    else {
        return 5;
    }
}
else {
    return 8;
}

Upvotes: 4

Related Questions