I have some questions about string comparison.I couln't find any answers concerning replace and substring methods in particular.So here is the code
public static void main(String args[]) {
if ("hello".substring(0) == "hello")
System.out.println("statement 1 is true");
if ("hello".substring(1) == "ello")
System.out.println("statement 2 is true");
if ("hello".replace('l', 'l') == "hello")
System.out.println("statement 3 is true");
if ("hello".replace('h', 'H') == "Hello")
System.out.println("statement 4 is true");
if ("hello".replace('h', 'H') == "hello".replace('h', 'H'))
System.out.println("statement 5 is true");
}
The output is:
statement 1 is true
statement 3 is true
Does the substring method create a new String().If so why is statement one true,yet 2 is not?Same question goes about statement 3 and 4.Thank you.
I assume you are aware of how string comparison works. So i'll try to explain what is happening.
Strings in java are immutable objects, so once created you can't change them.
To reduce overhead in creating the "same" string object over and over again, there is a pool of already used/created strings.
Now when you now compare if two string objects are the same it compares whether the objects themselves are the same. if you do "hello".substr(0) it will "create" a string object with "hello" in it. Since "hello" was already used, the string object containing "hello" is already in the string object pool. And if you now again "create" the string object "hello" to compare with, it will return the same object from the pool.
The same is happening with the "hello".replace("l","l") it will return the same "hello" string object like above.
But you can not rely on that, because the string-pool can get emptied at any time.
Further reading for "internalling strings" http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#intern()
BUT, if your question is about how to compare string themselves not the objects containing you strings, you should really use "hello".equals("hello") because then it will compare the real content. (As mentioned above)
If you compare strings with .equals()
(to test value equality) rather than ==
(which tests referential equality), your program will output different results.
You should not be comparing strings like that in java. == is comparing the string references instead of the strings itself. Use .equals()
method already defined for quality comparison of strings.
str1.equals("Hello");
The substring()
method (which was changed in Java 7), will always return a new object. The only exception to this is if it is to return the whole string (substring(0)
). Then, it will return it from the pool and the equality expression (==
) will evaluate to true. This is the reason why statement 1 is true, but statement 2 false.
An example.