The if statement evaluates a condition and, only if it is true, executes the statement that follows. There is nothing else required, which is what distinguishes it from if-else.
int age = 20;
if (age >= 18) {
System.out.println("Eligible to vote!");
System.out.println("Welcome to active citizenship.");
}With age at 20 both lines print. When the condition is false, the block is skipped entirely and execution simply continues after it.
int score = 45;
if (score >= 50) {
System.out.println("This line never prints.");
}Nothing is printed here, and that is the whole behaviour. There is no implicit "otherwise" and no error, so an if that never fires is entirely legal.
| Part | Purpose |
|---|---|
if | The keyword that starts the conditional |
() | Hold the condition, parentheses are mandatory |
| The condition | Must be a boolean expression |
| The body | One statement, or a block of statements in braces |
else | Optional, and not part of this statement |
The parentheses are not optional, which is a small syntactic difference from C-like languages that let you write if x > 0.
if (age >= 18) {
} // correct
if age >= 18 {
} // syntax error