Java programming course: 5.9 Conditionals using switch case

In the previous lesson you leant about the ternary operator.


Conditionals using switch case

An alternative structure to if…else… is the switch…case… block. You can only use this when testing for equality and for the integer primitives (byte, short, int, long and char) and their wrapper classes (Byte, Short, Integer, Long and Character), and for enum types. You can also test for equality on String objects:

public String dayName(int dayNumber) {
    String name;

    switch (dayNumber) {
        case 0:
            name = "Sunday";
            break;
        case 1:
            name = "Monday";
            break;
        case 2:
            name = "Tuesday";
            break;
        case 3:
            name = "Wednesday";
            break;
        case 4:
            name = "Thursday";
            break;
        case 5:
            name = "Friday";
            break;
        case 6:
            name = "Saturday";
            break;
        default:
            name = "* unknown *";
    }

    return name;
}
 

Note the following:

  • The switch statement references a suitable variable to be tested, which in this example is the method argument. You need an opening and closing brace to mark out the entire switch block
  • The case statement tests whether the variable is equal to the value specified. Note that that this is followed by a colon
  • The line(s) following the case are executed if the condition is met
  • You need to specify the break statement to prevent the following lines from being executed

If you do not specify break, then the following lines of code will be executed without any further conditional testing!

Example of switch case with a String object

Since Java 7 enables you can use the String type as the subject in a switch block:

String day = "Monday";

switch (day) {
    case "Monday":
        // do something for Monday
        break;
    default:
        // some other day
}
 

While there are many legitimate uses for if…else… and switch…case… blocks you should be aware that their use might possibly be an indication that you have not fully exploited the object-oriented facilities of Java, such as using inheritance and overriding methods.


In the next lesson you will learn about casting.

Next lesson: 5.10 Casting 


Print
×
Stay Informed

When you subscribe, we will send you an e-mail whenever there are new updates on the site.

Related Posts

 

Comments

No comments made yet. Be the first to submit a comment
Monday, 27 October 2025

Captcha Image