if
So far every line of a program ran every time. An if statement runs a block of code only when a condition is true:
int temperature = 31;
if (temperature > 30) {
System.out.println("Hot day: drink water.");
}
System.out.println("Temperature: " + temperature);
Hot day: drink water.
Temperature: 31- The condition goes in parentheses after
if. Here it'stemperature > 30, which is either true or false. - The block in braces
{ }runs only when the condition is true. Withtemperature = 25, the program would print only the second line. - The line after the block runs either way.
No semicolon after the condition
A semicolon right after if (...) ends the if there, with nothing in it. The block below it then runs every time, and Java doesn't warn about it:
int speed = 30;
if (speed > 50); {
System.out.println("Too fast!");
}
Too fast!Only 30, and yet "Too fast!". When an if seems to be ignored, check for this semicolon first.