Java Programming Tutorials

Java programming tutorials with many code examples!

Java Switch Case

Problem:

What is syntax for switch case statement in Java 7?

Solution:

In older Java versions switch-case statement worked only with primitive data types, like byte, short, char, and int.

Since Java 5 you can also use wrapper types for the primitive types i.e. Byte, Character, Short, and Integer. Moreover it accepts also enum types thus:

package com.farenda.solved;

import static java.lang.System.out;

// Sample enum to have something to work with:
enum Language {
    Java,
    Clojure,
    Python
}

public class JavaSolved {

    public static void main(String[] args) {
        // We have to refer through enum type name:
        Language lang = Language.Java;

        // Inside switch, can refer to enums by short names:
        switch (lang) {
        // "default" case can be in any place:
        default:      out.println("Unknown language: " + lang); break;
        // skipping "break" means to fallthrough to the next case
        case Java:    out.println("Java here!"); break;
        case Clojure: out.println("Clojure here!"); break;
        case Python:  out.println("Python here!"); break;
        }
    }
}

Let’s compile and run it:

$> javac src/com/farenda/solved/*.java -d out
$> java -cp out com.farenda.solved.JavaSolved
Java here!

Remember that you can’t mix types in switch-case statement, else you will receive compilation error:

Compiling: javac src/com/farenda/solved/*.java -d out
src/com/farenda/solved/JavaSolved.java:14: error: an enum switch case label must be the unqualified name of an enumeration constant
        case 1: System.out.println("Java here!"); break;
             ^
1 error

Since Java 7 you can also use switch with String types:

package com.farenda.solved;

import static java.lang.System.out;

public class JavaSolved {

    public static void selectLanguage(String lang) {
        switch (lang) {
        case "Java":    out.println("Java here!"); break;
        case "Clojure": out.println("Clojure here!"); break;
        case "Python":  out.println("Python here!"); break;
        }
    }

    public static void main(String[] args) {
        for (String lang : args) {
            selectLanguage(lang);
        }
    }
}

Let’s run it and see how switch on String types work in Java 7:

$> javac src/com/farenda/solved/*.java -d out
$> java -cp out com.farenda.solved.JavaSolved Java Python
Java here!
Python here!

Remember that String comparison is case sensitive.

Share with the World!