CodeGym /Courses /JAVA 25 SELF /Classic switch: syntax, examples

Classic switch: syntax, examples

JAVA 25 SELF
Level 10 , Lesson 3
Available

1. Introduction

Imagine this: you’re writing a program for a coffee shop. A user can choose a drink, and you need to react to that choice. You could, of course, use a bunch of if-else if-else, but it doesn’t look great:

if (choice == 1) 
{
    System.out.println("You chose espresso.");
} 
else if (choice == 2) 
{
    System.out.println("You chose cappuccino.");
} 
else if (choice == 3) 
{
    System.out.println("You chose latte.");
} 
else 
{
    System.out.println("No such drink.");
}

Admit it, it looks cumbersome. And what if there are 10 or 20 options? That’s where the switch statement comes to the rescue, letting you implement a choice among many options by a variable’s value elegantly and compactly.

Syntax of the classic switch

The switch syntax in Java looks like this:


switch (expression) 
{
    case value1:
        // actions if expression == value1
        break;
    case value2:
        // actions if expression == value2
        break;
    ...
    default:
        // actions if it doesn't match any case
        break;
}
Syntax of the switch statement in Java

Key elements:

  • switch (expression) — the expression whose result is compared with each case.
  • case value: — an option to compare the expression against.
  • break; — terminates execution of the switch block (otherwise there is “fall-through” to the next case).
  • default: — runs if none of the case labels matched.

2. Examples of using switch

Example 1: A classic — choosing a drink

Let’s implement a menu for a coffee shop:

import java.util.Scanner;

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

        System.out.println("Choose a drink:");
        System.out.println("1 - Espresso");
        System.out.println("2 - Cappuccino");
        System.out.println("3 - Latte");
        int choice = console.nextInt();

        switch (choice) 
        {
            case 1:
                System.out.println("You chose espresso.");
                break;
            case 2:
                System.out.println("You chose cappuccino.");
                break;
            case 3:
                System.out.println("You chose latte.");
                break;
            default:
                System.out.println("No such drink.");
                break;
        }
    }
}

What happens:

  • The user enters a drink number.
  • The value of the choice variable is compared with each case.
  • If it matches — the corresponding block runs, then break ends the switch execution.
  • If none matched — the default block runs.

Example 2: Switch on strings

There aren’t many types you can use inside a switch, but strings are allowed! That’s convenient for command menus:

import java.util.Scanner;

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

        System.out.println("Enter a command (start, stop, pause):");
        String command = console.nextLine();

        switch (command) 
        {
            case "start":
                System.out.println("Starting the program!");
                break;
            case "stop":
                System.out.println("Stopping the program.");
                break;
            case "pause":
                System.out.println("Pause.");
                break;
            default:
                System.out.println("Unknown command.");
                break;
        }
    }
}

Note: string comparison in a switch is case-sensitive! "Start" and "start" are different strings.

3. What types does the classic switch support?

In the classic switch, you can only use certain types:

  • Primitive integral types: byte, short, char, int
  • Enums: enum (we’ll talk about them in the next lecture)
  • Strings: String — comparisons are case-sensitive

You cannot use: boolean, float, double, arrays, arbitrary class objects (except enum and String).

Example with char

char grade = 'B';

switch (grade) 
{
    case 'A':
        System.out.println("Excellent!");
        break;
    case 'B':
        System.out.println("Good.");
        break;
    case 'C':
        System.out.println("Satisfactory.");
        break;
    default:
        System.out.println("Try again.");
        break;
}

4. Mandatory break: what happens if you forget it?

The most common beginner mistake is forgetting break;. Let’s see what happens:

int day = 2;

switch (day) 
{
    case 1:
        System.out.println("Monday");
        break;
    case 2:
        System.out.println("Tuesday");
    case 3:
        System.out.println("Wednesday");
        break;
    default:
        System.out.println("Unknown day");
        break;
}

Result:

Tuesday
Wednesday

Why? Because after case 2 there is no break, and execution falls through to the next case (this is called fall-through). Sometimes this is useful, but more often it’s a bug.

5. Grouping case: when several options behave the same

If several values need the same behavior, you can list them one after another:

int month = 1;

switch (month) 
{
    case 12:
    case 1:
    case 2:
        System.out.println("Winter");
        break;
    case 3:
    case 4:
    case 5:
        System.out.println("Spring");
        break;
    case 6:
    case 7:
    case 8:
        System.out.println("Summer");
        break;
    case 9:
    case 10:
    case 11:
        System.out.println("Fall");
        break;
    default:
        System.out.println("Unknown month");
        break;
}

Here: if month is 12, 1, or 2, the program prints "Winter".

6. Comparison: switch vs if-else

Scenario if-else switch
Many options Long chain, harder to read Concise, all options visible at a glance
Range comparisons Possible (if (x > 5 && x < 10)) Not possible, only specific values
Supported types Any Only certain ones (see above)
The break pitfall No Yes, you must watch for break

7. Common mistakes when working with switch

Error #1: forgot break
The most common source of bugs: you forgot break — and the code executes a different case than you expected.

Error #2: unsupported type
You try to use double, float, or boolean — the compiler will say “not allowed.”

Error #3: strings with different case
The user entered "Start", but you’re expecting "start" — the switch won’t match. It’s better to convert strings to a single case in advance:

switch (command.toLowerCase()) 
{
    case "start":
        // ...
}

Error #4: a variable in case instead of a constant
Only constants are allowed in a case. If you use a variable, you’ll get a compilation error.

Error #5: duplicate case labels
Two identical case values — the compiler won’t allow it.

1
Task
JAVA 25 SELF, level 10, lesson 3
Locked
Smart Office: Day Identification 📅
Smart Office: Day Identification 📅
1
Task
JAVA 25 SELF, level 10, lesson 3
Locked
Robot Control Panel 🤖
Robot Control Panel 🤖
1
Task
JAVA 25 SELF, level 10, lesson 3
Locked
Seasonal guide by month 🍂
Seasonal guide by month 🍂
1
Task
JAVA 25 SELF, level 10, lesson 3
Locked
Pocket calculator ➕
Pocket calculator ➕
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION