Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Java 7 switch statement with String use equals() method?

Java 7 supports switching with Strings like the code below

switch (month.toLowerCase()) { case "january":     monthNumber = 1;     break; case "february":     monthNumber = 2;     break; default:      monthNumber = 0;     break; } 

Does Java call the equals() method on each String case? Or it relies on == or intern()?

Is this simply equivalent to:

String month = month.toLowerCase(); if("january".equals(month)){ monthNumber = 1; }else if("february".equals(month)){ monthNumber = 1; }.. 

UPDATE:

The String in the switch expression is compared with the expressions associated with each case label as if the String.equals method were being used.

As the docs point out that the behavior is as if equals() is called.

like image 546
Narendra Pathai Avatar asked Sep 05 '13 12:09

Narendra Pathai


People also ask

Does Java switch Use equal?

Yes. Show activity on this post.

Does switch case Use equal?

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.

Does Java switch statement work with strings?

Yes, we can use a switch statement with Strings in Java.

Does equals () method consider strings Java and Java as equal?

Definition and UsageThe equals() method compares two strings, and returns true if the strings are equal, and false if not.


2 Answers

The docs say

The String in the switch expression is compared with the expressions associated with each case label as if the String.equals method were being used. 

Since it says as if my guess would be it does not though the internal implementation would be the same as .equals() method.

like image 135
Aniket Thakur Avatar answered Oct 05 '22 03:10

Aniket Thakur


The Java 7 switch statement actually generates bytecode that uses both the hashCode() and equals() methods. The hash code is used to generate faster switch lookups; i.e. to avoid a chain of equals checks like you would get with an if-else chain.

like image 25
Steinar Avatar answered Oct 05 '22 03:10

Steinar