How do I compare strings in Java?(Stackoverflow)

Question:

I’ve been using the==operator in my program to compare all my strings so far. However, I ran into a bug, changed one of them into.equals()instead, and it fixed the bug.

Is==bad? When should it and should it not be used? What’s the difference?

Answer:

==tests for reference equality.

.equals()tests for value equality.

Consequently, if you actually want to test whether two strings have the same value you should use.equals().

There are however a few situations where you can guarantee that two strings with the same value will be represented by the same object because ofString interning. Those cases are specified by theJava Language Specification.

==is for testing whether two strings are the sameobject.

It is important to note that==is a bit cheaper thanequals()(a single reference comparison instead of a method call), thus, in situations where it is applicable (i.e. you can guarantee that you are only dealing with interned strings) it can present an important performance improvement.However, these situations are rare.

More information here:What’s wrong with using == to compare floats in Java?

,今天又是美好的一天,我要展示出我优秀的一面。不必一味讨好别人

How do I compare strings in Java?(Stackoverflow)

相关文章:

你感兴趣的文章:

标签云: