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)?
Asked
Active
Viewed 1,590 times
0
-
https://docs.oracle.com/javase/specs/jls/se9/html/jls-14.html#jls-14.11 – whatamidoingwithmylife Dec 02 '17 at 17:47
-
Read this: https://stackoverflow.com/questions/10836055/why-is-the-switch-statement-faster-than-if-else-for-string-in-java-7 – DoesData Dec 02 '17 at 18:38
1 Answers
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