0

I am using switch{case ()} with String in java, and so far it seems to be working perfectly. But I want to confirm before continuing too much; is this safe?

I mean, I know that I should not be doing if ("hi" == "hi"), but should be doing "hi".equals ("hi") because String refers to a reference point...

I am not too sure how switch works, and I have not been able to confirm from any of my sources...

Thank you!!

8
  • 2
    yes and no, depending on the java version (1.7 up) Commented Oct 10, 2016 at 6:50
  • What do you mean by java version? Commented Oct 10, 2016 at 6:51
  • 2
    @Orange: Um, the version of the Java language you're using... Commented Oct 10, 2016 at 6:52
  • So if I have java later than version 7, my method should be safe right? Commented Oct 10, 2016 at 6:53
  • Indeed, and note that Java is clever enough to compare the string contents, not the references. Commented Oct 10, 2016 at 6:54

1 Answer 1

0

According to the language specification (emphasis mine):

If one of the case constants is equal to the value of the expression, then we say that the case matches, and all statements after the matching case label in the switch block, if any, are executed in sequence.

This implies that the switch case is evaluated using equals, not ==.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.