tags:

views:

178

answers:

5

How come this is not possible? I am getting illegal start of expression.

(s1.charAt(i) == ' ') ? i++ : break;
+3  A: 

The ternary operator is an expression, not a statement. Use if ... else ... for this.

Marcelo Cantos
+9  A: 

You cannot use break in part of a ternary conditional expression as break isn't an expression itself, but just a control flow statement.

Why not just use an if-else construct instead?

if (s1.charAt(i) == ' ') {
    i++;
} else {
    break;
}
BoltClock
+14  A: 

The thing to understand here is that the ?: operator is used to return a value. You're basically calling a function that looks like this in that line:

anonymous function:
    if(s1.charAt(i) == ' '):
        return i++;
    else:
        return break;

Makes no sense, right? The ?: operator was only designed as a shorthand for if/else return statements like the above, not a replacement of if/else altogether.

Axidos
Not quite correct, IMHO: Evaluating an expression (reducing it, if you will) also renders a value. The two terms you're using basically boil down to the same thing. The important thing here is that **`break` is not a value**, but a control flow _statement_.
stakx
I think you're right there; **?:** _is_ used to evaluate expressions as a side-effect. My point was that the focus is on returning a value rather than merely having code evaluated or not. I've reworded it to try to make myself clearer.
Axidos
+2  A: 

Of course it works. But it's an operator. Since when was a statement such as 'break' an operand?

EJP
+1  A: 

I recommend avoiding the ternary (?:) operator EXCEPT for simple assignments. In my career I have seen too many crazy nested ternary operators; they become a maintenance headache (more cognitive overload - "don't make me think!").

I don't ban them on my teams, but recommend they are used judiciously. Used carefully they are cleaner than a corresponding if/else construct: -

public int ifFoo() {
    int i;

    if( isSomethingTrue()) {
        i = 5;
    }
    else {
        i = 10;
    }

    return i;
}

Compared to the ternary alternative: -

public int ternaryFoo() {
    final int i = isSomethingTrue()
                ? 5
                : 10;

    return i;
}

The ternary version is: -

  • Shorter
  • Easier to understand (my opinion, of course!)
  • Allows the variable to be "final"; which simplifies code comprehension; in a more complex method, someone reading the code knows no further code will try and modify the variable - one thing less to worry about.
DecaniBass
`return isSomethingTrue() ? 5 : 10;` is sooo much cleaner that 10 lines if statement and that useless local variable.
Willi
I only put the local variable in so I can breakpoint on that line if I ever need to debug. Not too fussed, either way!
DecaniBass
The variable can be final either way actually, as long as it is assigned via all code paths before use.
EJP