In switch case, What is string in Java?

Switch Statement in Java

Starting from JDK 7, we can use string literals/constants to control switch statements, which is impossible in C/C++. Using a string-based switch is an improvement over the equivalent sequence of using if/else statements.

Important Points:

  • Expensive operation: In terms of execution, switching strings can be more expensive than switching primitive data types. Therefore, it is best to open the string only when the control data is already in the form of a string.
  • The string should not be NULL: Ensure that the expression in any switch statement is not null when processing the string to prevent NullPointerException from being thrown at runtime.
  • Case Sensitive Comparison: The switch statement compares the String object in its expression with the expression associated with each case label as if it used the String.equals method; therefore, the comparison of String objects in the switch statement is case sensitive.
  • Better than if-else: The bytecode generated by the Java compiler from switch statements that use String objects is generally more efficient than the bytecode generated 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";
		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