How come this is not possible? I am getting illegal start of expression.
(s1.charAt(i) == ' ') ? i++ : break;
How come this is not possible? I am getting illegal start of expression.
(s1.charAt(i) == ' ') ? i++ : break;
The ternary operator is an expression, not a statement. Use if ... else ...
for this.
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;
}
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.
Of course it works. But it's an operator. Since when was a statement such as 'break' an operand?
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: -