Java Switch with String

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

String in Switch Statement

In Java 7, Java allows you to use string objects in the expression of switch statement. In order to use string, you need to consider the following points:

  • It must be only string object.
  1. Object game = "Hockey"; // It is not allowed  

  2.     String game = "Hockey"; // It is OK.  

  • String object is case sensitive.
  1. "Hickey" and "hocker" are not equal.  

  • No Null object

be careful while passing string object, passing a null object cause to NullPointerException.


String in Switch Statement Example 1

  1. public class StringInSwitchStatementExample {  
  2.     public static void main(String[] args) {  
  3.         String game = "Cricket";  
  4.         switch(game){  
  5.         case "Hockey":  
  6.             System.out.println("Let's play Hockey");  
  7.             break;  
  8.         case "Cricket":  
  9.             System.out.println("Let's play Cricket");  
  10.             break;  
  11.         case "Football":  
  12.             System.out.println("Let's play Football");  
  13.         }  
  14.     }  
  15. }  

Output:

Let's play Cricket

String in Switch Statement Example 2

  1. public class StringInSwitchStatementExample {  
  2.     public static void main(String[] args) {  
  3.         String game = "Card-Games";  
  4.         switch(game){  
  5.         case "Hockey"case"Cricket"case"Football":  
  6.             System.out.println("This is a outdoor game");  
  7.             break;  
  8.         case "Chess"case"Card-Games"case"Puzzles"case"Indoor basketball":  
  9.             System.out.println("This is a indoor game");  
  10.             break;  
  11.         default:   
  12.             System.out.println("What game it is?");  
  13.         }  
  14.     }  
  15. }  

Output:

This is a indoor game