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 does an extra semicolon make the conditional statement ineffective?ComputerScienceOne · Computing a Logarithm
- How do if, else, and else if statements work in Java?ComputerScienceOne · If, If-Else, If-Else-If Statements
- How do if, if-else, and if-else-if statements work in PHP?ComputerScienceOne · If, If-Else, If-Else-If Statements
- Why should you avoid a semicolon after a while-loop condition?ComputerScienceOne · While Loops
- Why should a while-loop condition not end with a semicolon in PHP?ComputerScienceOne · While Loops
- Why should you avoid a semicolon after a while condition?ComputerScienceOne · While Loops
- How are if, if-else, and if-else-if statements written in C?ComputerScienceOne · If, If-Else, If-Else-If Statements
- What are examples of if, if-else, and if-else-if statements in Java?ComputerScienceOne · If, If-Else, If-Else-If Statements