How to use this boolean in an if statement?

if(stop = true) should be if(stop == true), or simply (better!) if(stop).

This is actually a good opportunity to see a reason to why always use if(something) if you want to see if it’s true instead of writing if(something == true) (bad style!).

By doing stop = true then you are assigning true to stop and not comparing.

So why the code below the if statement executed?

See the JLS – 15.26. Assignment Operators:

At run time, the result of the assignment expression is the value of
the variable after the assignment has occurred. The result of an
assignment expression is not itself a variable.

So because you wrote stop = true, then you’re satisfying the if condition.

Leave a Comment