Concept

Why can an extra semicolon make an if statement behave incorrectly?

ComputerScienceOne / Computing a Logarithm

"Some compilers may give a warning, but this is valid Java; it will compile and it will run. However, it will end up printing x is less than 10, even though x = 15! Recall that a conditional statement binds to the executable statement or code block immediately following it. In this case, we’ve provided an empty executable statement ended by the semicolon. The code is essentially equivalent to int x = 15; if(x < 10) { } System.out.println(\"x is less than 10\"); Which is obviously not what we wanted. The semicolon ended up binding to the empty executable statement, and the code block containing the print statement immediately followed, but was not bound to the conditional statement which is why the print statement executed regardless of the value of x."

Related Ideas

Why can an extra semicolon make an if statement behave incorrectly? | ComputerScienceOne | Bifalgorithm | Bifalgorithm