Nanfeng

Notes on software development, code, and curious ideas

Conditional Statements in Java

if

An if block runs only when its Boolean condition is true:

1
2
3
if (condition) {
// Runs when condition is true.
}

Example:

1
2
3
4
int age = 18;
if (age >= 18) {
System.out.println("Adult");
}

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
2
3
4
5
6
7
int age = 15;

if (age >= 18) {
System.out.println("Adult");
} else {
System.out.println("Minor");
}

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
2
3
4
5
6
7
8
9
10
11
int score = 70;

if (score >= 90) {
System.out.println("Excellent");
} else if (score >= 70) {
System.out.println("Good");
} else if (score >= 60) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}

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
2
3
4
5
6
7
8
int age = 25;
boolean hasRequiredDocument = true;

if (age >= 18) {
if (hasRequiredDocument) {
System.out.println("Eligible");
}
}

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
2
3
4
5
6
7
8
9
10
11
12
int value = 2;

switch (value) {
case 1:
System.out.println("One");
break;
case 2:
System.out.println("Two");
break;
default:
System.out.println("Another value");
}

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
2
3
4
5
String label = switch (value) {
case 1 -> "One";
case 2 -> "Two";
default -> "Another value";
};
+