views:

80

answers:

3

When I write boolean bool = aString.indexOf(subString) != -1 Eclipse did not complain, does it mean that it is the same as boolean bool = aString.indexOf(subString) != -1 ? true : false?

+9  A: 

Yes. A comparison produces a boolean value, and it can be assigned to a variable just as any other value.

The second form (with the ternary ?: operator) is redundant and should not be used.

Stylistically, I normally enclose boolean expressions in parentheses when assigning them to values, as

boolean bool = (aString.indexOf(subString) != -1);

in order to make a strong visual distinction between the two operators using the = symbol, but this is not required.

Tyler McHenry
+1  A: 

Yes both syntax are equivalent.

Just use parenthesis to be clear or more readable.

boolean bool = (aString.indexOf(subString) != -1);
Matthieu BROUILLARD
+1  A: 

Yes certainly. A boolean expression returns a boolean value. That's why it can be used in if statements and so on because they expect true or false outcomes.

BalusC