if
An if block runs only when its Boolean condition is true:
1 | if (condition) { |
Example:
1 | int age = 18; |
Java allows braces to be omitted for a single statement, but retaining them usually makes maintenance safer and clearer.
if and else
Use else for the alternative branch:
1 | int age = 15; |
For a short value selection, Java also provides the conditional operator:
1 | String status = age >= 18 ? "Adult" : "Minor"; |
else if
An else if chain tests conditions from top to bottom and executes only the first matching branch:
1 | int score = 70; |
Although 70 is also greater than 60, the Good branch matches first, so later branches are skipped.
Nested conditions
An if block may contain another condition:
1 | int age = 25; |
Deep nesting can become hard to read; guard clauses or extracted methods are often clearer.
switch
switch is useful when one expression is compared with a fixed set of values:
1 | int value = 2; |
Without break, a traditional case falls through into the next one. Java also supports switching over strings and enums. Modern Java versions provide switch expressions with arrow labels:
1 | String label = switch (value) { |