Java
Module 4: Control Flow & LoopsBeginner22 min read

Conditional Statements (if, else-if, Switch & Modern Switch)

Control program branching with if-else ladders, classic switch-case, and modern Java 14+ switch expressions with arrow syntax.

Key Takeaways & Core Concepts
  • Build decision trees using if, if-else, nested if, and else-if ladders.
  • Understand classic switch fall-through behavior and why break is required.
  • Use modern Java 14+ Switch Expressions with arrow syntax (->) and yield.
  • solve this:

Introduction

Conditional statements direct execution down different paths based on runtime boolean expressions or discrete values. Writing clean branching logic—and preferring flat early returns over deeply nested if blocks—keeps Java code readable.

Modern Switch Expression & Else-If Ladder
1public class Main {
2 public static void main(String[] args) {
3 int score = 86;
4 String grade;
5 if (score >= 90) grade = "A+";
6 else if (score >= 80) grade = "A";
7 else if (score >= 70) grade = "B";
8 else grade = "C";
9
10 String day = "SAT";
11 String dayType = switch (day) {
12 case "SAT", "SUN" -> "Weekend";
13 case "MON", "TUE", "WED", "THU", "FRI" -> "Weekday";
14 default -> "Invalid";
15 };
16
17 System.out.println("Grade: " + grade + " | Day: " + dayType);
18 }
19}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
19 lines
Note: Arrow cases (`->`) in switch expressions eliminate `break` boilerplate and prevent fall-through bugs.

Learning Objectives

  • Build decision trees using if, if-else, nested if, and else-if ladders.
  • Understand classic switch fall-through behavior and why break is required.
  • Use modern Java 14+ Switch Expressions with arrow syntax (->) and yield.

Classic Switch vs Modern Switch Expressions (Java 14+)

In classic switch, omitting break; causes execution to "fall through" into the next case, a notorious source of bugs. Modern Switch Expressions solve this:

  • Use case "SAT", "SUN" -> "Weekend"; (no break needed, never falls through).
  • Can return a value directly into a variable, and the compiler enforces exhaustiveness (requiring default when not all enum/sealed values are covered).
  • Supports int, char, byte, short, String, enum, and in Java 21+, Pattern Matching for switch!
Practice & AssessmentJava Programming Tutorial

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 0 correct(0 attempted)