When you learn Java in school, teachers will remind you to use a.equals(b) instead of a == b to compare two strings a and b. Because in Java, comparing two objects with == will only return true if they share the same memory address.
However, @Crazyconv suggested me to run the following code in Java tonight.
String a = "Hello World";
String b = "Hello World";
System.out.println(a==b);
System.out.println(a.equals(b));It turns out that this piece of code would print two true.
What’s the magic behind?
The String Pool
Actually, there is someting called String Pool in Java. When the Java compiler (not the JRE during runtime) notice two identical strings in your code, it will only create one object of that string to improve performance. There is another example below which would output true.
String s = "a" + "bc";
String t = "ab" + "c";
System.out.println(s == t);Code from Stack Overflow
Force to create different strings
The behaviour Java compiler is safe because strings are immutable in Java. That is to say you cannot change the content of a string without create a new object. In the first example code in this post, for example, if you want to change String b to “Another String”, you will create a new object of “Another String” and make the variable b refer to the new object, so the String a will not be affected.
However, you can force the Java compiler to create two objects for the same string by using the new keyword. There is an example below
String a = new String("Hello World");
String b = new String("Hello World");
System.out.println(a==b);
System.out.println(a.equals(b));In this example, the outputs would be false and true.
For beginners
You are still encourage always to use .equals method of String to make the comparison, because only it will give you the correct result for strings created during runtime.