Monday, 15 September 2014

How do I compare strings in Java? -


I use the == operator in my program to compare all the stars so far I am doing However, I went to a bug, one of them was changed to .equals () , and it fixed the bug.

What is == bad? When should this happen and it should not be used? Reference for reference equality (whether they are)

== ).

.equals () test for value equality (whether they are rational "equivalent").

Checks for tap before calling .equals () , so you (available as JDK 7 also available).

As a result, if you want to check whether the two strings have the same value, then you might

Objects.equals () .

  would like to use. String ("exam"). Equal ("test") // - & gt; True // ... but they are not the same thing new string ("test") == "test" // - & gt; False // ... neither new string ("test") == new string ("test") // - & gt; False // ... but this is because the text is literally inserted by the // compiler and thus the same object "test" == "test" // - & gt; True // ... but you should actually call Objects.equals () Objects.equals ("test", new string ("test") - // - & gt; True objects Equal (empty, "test") // - & gt; False  

You almost want to use always Objects.equals () . In the rare situation where you know you are working with the string, you can == Use same class string . The reason for this is that string literals - or, more commonly, the strings that are values ​​of continuous expression () - are "embedded" so that the method for sharing unique code is String.intern .

Such examples can also be found.


No comments:

Post a Comment