0

I have one query related to switch case with string, How jvm work internally in case of switch case with string(feature come in java 1.7)?

1 Answers1

3

The switch statement compares the String object in its expression with the expressions associated with each case label as if it were using the String.equals method; consequently, the comparison of String objects in switch statements is case sensitive.

Java Switch case uses String.equals() method to compare the passed value with case values.

According to Java 7 documentation for Strings in Switch, The Java compiler generates generally more efficient bytecode from switch statements that use String objects than from chained if-then-else statements.

See this example:

String fruit ="Mango";       

    switch (fruit) {
    case "Apple": System.out.println("It's Apple : "+"Apple".hashCode());           
                  break;
    case "mango": System.out.println("It's mango : "+"mango".hashCode());
                  break;
    case "Mango": System.out.println("It's Mango : "+"Mango".hashCode());
                  break;
    }

JVM converted this as following:

    String fruit = "Mango";

    String str1;
    switch ((str1 = fruit).hashCode()) {
    case 63476538:
        if (str1.equals("Apple")) {
            System.out.println("It's Mango : " + "Mango".hashCode());
             }
        break;
    case 74109858:
        if (str1.equals("Mango")) {
            System.out.println("It's Mango : " + "Mango".hashCode());
        }
        break;
    case 103662530:
        if (!str1.equals("mango")) {
            System.out.println("It's mango : " + "mango".hashCode());
            return;
        }
        break;
    }
Neha Shettar
  • 703
  • 10
  • 28