Can we use Switch statement with Strings in java?

Java 8Object Oriented ProgrammingProgramming

switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case.

Syntax

switch(expression) {
   case value :
      // Statements
      break;
   case value :
      // Statements
      break;
      // You can have any number of case statements.
      default :
      // Statements
}

Strings in switch

Yes, we can use a switch statement with Strings in Java. While doing so you need to keep the following points in mind.

  • It is recommended to use String values in a switch statement if the data you are dealing with is also Strings.
  • The expression in the switch cases must not be null else, a NullPointerException is thrown (Run-time).
  • Comparison of Strings in switch statement is case sensitive. i.e. the String you have passed and the String of the case should be equal and, should be in same case (upper or, lower).

Example

Following example demonstrates the usage of String in switch statement.

import java.util.Scanner;
public class SwitchExample {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Available models: Activa125(act125), Activa5G(act5g),"
         + " Accesses125(acc125), Vespa(ves), TvsJupiter(jup)");
      System.out.println("Select one model: ");
      String model = sc.next();
      switch (model) {
         case "act125":
            System.out.println("The price of activa125 is 80000");
            break;
         case "act5g":
            System.out.println("The price of activa5G is 75000");
            break;
         case "acc125":
            System.out.println("The price of access125 is 70000");
            break;
         case "ves125":
            System.out.println("The price of vespa is 90000");
            break;
         case "jup":
            System.out.println("The price of tvsjupiter is 73000");
            break;
         default:
            System.out.println("Model not found");
            break;
      }
   }
}

Output

Available models: Activa125(act125), Activa5G(act5g), Accesses125(acc125), Vespa(ves), TvsJupiter(jup)
Select one model:
act125
The price of activa125 is 80000
raja
Published on 05-Jul-2019 17:37:57
Advertisements