Is it possible to assign a test result to a boolean variable in Java?

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

+3
source share
3 answers

Yes. Comparison gives a logical value and can be assigned to a variable in the same way as any other value.

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

Stylistically, I usually enclose logical expressions in parentheses when assigning values ​​to them, since

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

to make a strong visual distinction between two statements using a symbol =, but this is not required.

+9

, .

, .

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

Yes of course. A boolean expression returns a boolean value. Therefore, it can be used in operators if, etc., because they expect results trueor false.

+1
source

Source: https://habr.com/ru/post/1747047/


All Articles