Java switch case with string

Let’s learn java switch case with string.

Java switch case with string

Since JDK 7 string literal was used in switch case. String in switch statement is an expensive operation when we compare with primitive data types.

Passing null to String object in switch statement expression can throw NullPointerException.

Object name = "Cricket"; // not allowed  
String name = "Cricket"; // allowed  

String object is case sensitive.
"Cricket" and "cricket" are not equal.  
Null object is not allowed.


Here comparison is case sensitive. Because expression in switch statement compares String object with each label using String.equals() method.

String in switch case is better than if-else statement. Now let’s see example on java switch case with string.

public class SwitchCaseWithString 
{
   public static void main(String[] args) 
   {
      String str = "twelve"; 
      switch(str) 
      { 
         case "ten": 
             System.out.println("ten"); 
             break;
         case "eleven": 
             System.out.println("eleven"); 
             break;
         case "twelve": 
             System.out.println("twelve"); 
             break; 
         default: 
             System.out.println("doesn't match"); 
      }
   }
}


Output:

twelve