Notice
I wrote this article and was originally published on Qiita on 31 August 2021.
First please read this if you don't sure how to use == operator for object.
Example from The Java® Language Specification
Got from here.
package testPackage;
class Test {
public static void main(String[] args) {
String hello = "Hello", lo = "lo";
System.out.print((hello == "Hello") + " "); // (1)
System.out.print((Other.hello == hello) + " "); // (2)
System.out.print((other.Other.hello == hello) + " "); // (3)
System.out.print((hello == ("Hel"+"lo")) + " "); // (4)
System.out.print((hello == ("Hel"+lo)) + " "); // (5)
System.out.println(hello == ("Hel"+lo).intern()); // (6)
}
}
class Other { static String hello = "Hello"; }
package other;
public class Other { public static String hello = "Hello"; }
The output is
true true true true false true
Things you need to know about String class
- String object is immutable
- A pool of strings, initially empty, is maintained privately by the class String. You may use intern() for looking up reference (Output of (6))
- All String constants will refer to the same String instance if the values are the same during compile time, no matter what package is in. And a reference will be stored in pool stated in point 2 (Output of (1), (2), (3), (4))
- New String object will be created during runtime (Output of (5))
Suggestion
Don't use == operator for checking if value of two String objects are equal. Please use equals() instead.