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
?
views:
80answers:
3
+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
2010-05-25 16:07:54
+1
A:
Yes both syntax are equivalent.
Just use parenthesis to be clear or more readable.
boolean bool = (aString.indexOf(subString) != -1);
Matthieu BROUILLARD
2010-05-25 16:07:54
+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
2010-05-25 16:08:11