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.

Here string should not be null in switch statement expression to prevent NullPointerException.

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 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