Skip to content
Related Articles

Related Articles

Improve Article

String in Switch Case in Java

  • Difficulty Level : Basic
  • Last Updated : 10 Mar, 2018
Geek Week

Switch Statement in Java

Beginning with JDK 7, we can use a string literal/constant to control a switch statement, which is not possible in C/C++. Using a string-based switch is an improvement over using the equivalent sequence of if/else statements.
Important Points:

  • Expensive operation: Switching on strings can be more expensive in term of execution than switching on primitive data types. Therefore, it is best to switch on strings only in cases in which the controlling data is already in string form.
  • String should not be NULL: Ensure that the expression in any switch statement is not null while working with strings to prevent a NullPointerException from being thrown at run-time.
  • Case Sensitive Comparison: The switch statement compares the String object in its expression with the expressions associated with each case label as if it were using the String.equals method; consequently, the comparison of String objects in switch statements is case sensitive.
  • Better than if-else: The Java compiler generates generally more efficient bytecode from switch statements that use String objects than from chained if-then-else statements.

// Java program to demonstrate use of a
// string to control a switch statement.
public class Test 
    public static void main(String[] args)
        String str = "two";
            case "one":
            case "two":
            case "three":
                System.out.println("no match");



This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :