Skip to main content

4.1 Conditional Statements

Conditional statements are used to change the execution path inside a block { } based on the result of a condition. The two main types are if statements and switch statements. Using conditionals effectively lets you express complex business logic in clear, readable code.

1. Basic if Statement Structure

The if statement is the most fundamental conditional. It executes the block only when the condition is true.

Simple if Statement

int score = 85;

if (score >= 60) {
System.out.println("You passed!");
}
// If the condition is false, the block is skipped.
Omitting Braces

If there is only one statement to execute, the braces can be omitted. However, it is a good habit to always use braces, as omitting them often leads to bugs when statements are added later.

if (score >= 60)
System.out.println("Pass!"); // Braces can be omitted, but not recommended

if-else Statement

Executes different code depending on whether the condition is true or false.

int score = 45;

if (score >= 60) {
System.out.println("You passed!");
} else {
System.out.println("You failed. Better luck next time!");
}

if-else if-else Chain

Used when checking multiple conditions in order. Conditions are evaluated from top to bottom, and only the first true block is executed.

int score = 85;

if (score >= 90) {
System.out.println("Grade A.");
} else if (score >= 80) { // less than 90 but at least 80
System.out.println("Grade B.");
} else if (score >= 70) {
System.out.println("Grade C.");
} else if (score >= 60) {
System.out.println("Grade D.");
} else { // everything below 60
System.out.println("Grade F.");
}
// Output: Grade B.

2. Nested if Statements

You can write another if statement inside an if block. There is no limit to the nesting depth, but deeply nested code becomes very hard to read.

int score = 95;
char opt = ' ';

if (score >= 90) {
// Outer if: 90 or above
if (score >= 98) {
opt = '+'; // 98 or above: A+
} else if (score < 94) {
opt = '-'; // 90~93: A-
}
// 94~97: plain A (opt remains ' ')
}
System.out.println("Your grade is A" + opt);
// Output: Your grade is A (score is 95, so opt is a space)
Nested if Readability Issues

When nesting goes 3 levels deep or more, it becomes difficult to follow the code flow. It is recommended to reduce nesting using the early return pattern or by separating the logic.

// Bad example: 3 levels of nesting
if (user != null) {
if (user.isActive()) {
if (user.hasPermission()) {
doSomething();
}
}
}

// Good example: Remove nesting with early return
if (user == null) return;
if (!user.isActive()) return;
if (!user.hasPermission()) return;
doSomething();

3. switch Statement (Traditional Style, Before Java 14)

When there are many possible values to check, a switch statement is much more readable and faster than multiple if-else chains. A switch statement checks for an exact value match, not a condition.

Basic Structure

int month = 4;
String season;

switch (month) {
case 3:
case 4:
case 5:
season = "Spring";
break; // exit the switch block
case 6:
case 7:
case 8:
season = "Summer";
break;
case 9:
case 10:
case 11:
season = "Autumn";
break;
default:
// executed when no case matches
season = "Winter";
}
System.out.println("Month " + month + " is " + season + "."); // Month 4 is Spring.

Types Allowed in a switch Statement

TypeExample
byte, short, intswitch(score)
charswitch(grade)
String (Java 7+)switch(command)
enumswitch(season)
long, float, double cannot be used in switch

long, float, and double cannot be used in switch expressions. Use if statements for these types.

4. Fall-Through Bug: Watch Out for Missing break

The most common mistake in switch statements is forgetting break. Without break, execution falls through from the matched case into the next case, causing a fall-through bug.

int day = 2; // Tuesday
String result = "";

switch (day) {
case 1:
result += "Monday ";
// break missing!
case 2:
result += "Tuesday ";
// break missing!
case 3:
result += "Wednesday ";
break; // exits here
case 4:
result += "Thursday ";
break;
}
System.out.println(result);
// Expected: "Tuesday "
// Actual output: "Tuesday Wednesday " <- fall-through bug!

Intentional Fall-Through

Sometimes fall-through is used intentionally.

int month = 4;
int days;

switch (month) {
case 1: case 3: case 5: case 7:
case 8: case 10: case 12:
days = 31;
break;
case 4: case 6: case 9: case 11:
days = 30;
break;
case 2:
days = 28; // ignoring leap year
break;
default:
days = -1; // invalid month
}
System.out.println("Month " + month + " has " + days + " days."); // Month 4 has 30 days.

5. Conditional (Ternary) Operator ?:

A shorthand for if-else. Using it for simple value selection makes code more concise.

// Syntax: (condition) ? value if true : value if false

int score = 75;

// if-else style
String result1;
if (score >= 60) {
result1 = "Pass";
} else {
result1 = "Fail";
}

// Ternary operator style (same result)
String result2 = (score >= 60) ? "Pass" : "Fail";

System.out.println(result2); // Pass
// Nested ternary operator (watch out for readability)
int score = 85;
String grade = (score >= 90) ? "A" :
(score >= 80) ? "B" :
(score >= 70) ? "C" : "F";
System.out.println("Grade: " + grade); // Grade: B
Avoid Overusing the Ternary Operator

Nesting ternary operators degrades readability. For 3 or more conditions, an if-else if chain or switch is clearer.

6. Choosing Between if and switch

SituationRecommended
Range conditions (score >= 90)if-else if
Comparing specific values (3 or more)switch
Two-way choiceif-else or ternary operator
Complex compound conditions (&&, ||)if-else if
Branching on an enum typeswitch expression (Java 14+)

7. Practical Example 1: Grade Calculator

A program that calculates a letter grade (A/B/C/D/F) from a score.

import java.util.Scanner;

public class GradeCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter a score (0~100): ");
int score = scanner.nextInt();

// Input validation
if (score < 0 || score > 100) {
System.out.println("Invalid score. Please enter a value between 0 and 100.");
scanner.close();
return;
}

String grade;
String comment;

if (score >= 90) {
grade = "A";
comment = "Excellent!";
} else if (score >= 80) {
grade = "B";
comment = "Well done!";
} else if (score >= 70) {
grade = "C";
comment = "Average.";
} else if (score >= 60) {
grade = "D";
comment = "Keep trying.";
} else {
grade = "F";
comment = "Retake required.";
}

System.out.println("Score: " + score);
System.out.println("Grade: " + grade);
System.out.println(comment);

scanner.close();
}
}

Sample run:

Enter a score (0~100): 85
Score: 85
Grade: B
Well done!

8. Practical Example 2: Daily Schedule Printer (Using switch)

import java.util.Scanner;

public class DailySchedule {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the day (Mon/Tue/Wed/Thu/Fri/Sat/Sun): ");
String day = scanner.next();

String schedule;
String type;

switch (day) {
case "Mon":
schedule = "Team meeting at 9 AM, weekly planning";
type = "Weekday";
break;
case "Tue":
schedule = "Code review at 2 PM";
type = "Weekday";
break;
case "Wed":
schedule = "Lunch team building, afternoon tech seminar";
type = "Weekday";
break;
case "Thu":
schedule = "1:1 meeting, sprint progress check";
type = "Weekday";
break;
case "Fri":
schedule = "Sprint retrospective, deployment prep";
type = "Weekday";
break;
case "Sat":
schedule = "Personal project, exercise";
type = "Weekend";
break;
case "Sun":
schedule = "Family time, preparation for next week";
type = "Weekend";
break;
default:
schedule = "Unknown day.";
type = "Error";
}

System.out.println("[" + type + "] " + day + " schedule: " + schedule);
scanner.close();
}
}

Sample run:

Enter the day (Mon/Tue/Wed/Thu/Fri/Sat/Sun): Wed
[Weekday] Wed schedule: Lunch team building, afternoon tech seminar

9. Practical Example 3: Login System Simulation

A practical example of nested conditional statements.

public class LoginSystem {
public static void main(String[] args) {
String inputId = "admin";
String inputPw = "1234";

// Assume these are retrieved from a database
String correctId = "admin";
String correctPw = "admin123";
boolean isAccountLocked = false;
int loginAttempts = 3;

if (isAccountLocked) {
System.out.println("Account is locked. Please contact the administrator.");
} else {
if (inputId.equals(correctId)) {
if (inputPw.equals(correctPw)) {
System.out.println("Login successful! Welcome, " + inputId + ".");
} else {
System.out.println("Wrong password. Attempts remaining: " + (loginAttempts - 1));
}
} else {
System.out.println("This ID does not exist.");
}
}
}
}
Pro Tips

Conditional Optimization Principles:

  1. Place the most frequent condition first— reduces the average number of comparisons.
  2. Extract complex conditions into variables— name the condition like boolean isValid = score >= 0 && score <= 100;.
  3. Use switch expressions (Java 14+)— completely eliminates fall-through bugs of traditional switch.
  4. Null check first— write if (str != null && str.equals("value")) in that order to prevent NullPointerException.