Java string in switch case

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: Including strings at run time can be more expensive than inserting primitive data types. Therefore, it is best to only include strings when the control data is already in string form.
  • String should not be NULL: Make sure the expression in each toggle statement is non-null when working with strings to avoid throwing a NullPointerException at run time.
  • Case Sensitive Comparison: The toggle operator compares the string object in its expression with the expression assigned to the label as if the String.equals method was used; Therefore, when comparing string objects in the switching operator, it is case-sensitive.
  • Better than if-else: Java compilers typically generate more efficient bytecode from the switch operator which uses a string object than from the if-then-else string operator.
// 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";
		switch(str)
		{
			case "one":
				System.out.println("one");
				break;
			case "two":
				System.out.println("two");
				break;
			case "three":
				System.out.println("three");
				break;
			default:
				System.out.println("no match");
		}
	}
}

Output:

two

 

Submit Your Programming Assignment Details