+ 2
Strings and == ?! (Java)
String a = new String("ABC"); String b = "ABC"; String c = " AB"+"C"; if(a == b)//....... if(a == "ABC")//...... if(b == "ABC")//...... I've seen a lot of these in the challenges and can't understand how it really works. I know how (==) works with objects and that it returns true if both references points to the same object. But how does it works with Strings?
4 ответов
+ 14
Java uses a String pool to make sure it doesn't store String objects with identical values twice. So you can have multiple variables that point to the same object in memory.
But if you force Java to create a new String object by using the new keyword, it does. And then it doesn't change the reference to an existing object with the same value.
That's the point where checking Strings for value equality doesn't work with ==.
The method equals always checks the String values for equality, so it is better to use that method.
+ 9
And don't use
new String ("bla")
if you don't know what you're doing ^^
+ 3
I only know that many people misunderstood the use it for checking string content equality, most answers recommend the use of equal method for string comparison. I suppose you already know that, sorry I can't explain details, just what I know.
+ 3
@Tashi, thank you so much...