Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I assign test result to a boolean variable in Java?

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?

like image 249
derrdji Avatar asked Dec 10 '22 15:12

derrdji


1 Answers

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.

like image 63
Tyler McHenry Avatar answered Feb 17 '23 18:02

Tyler McHenry