I have a simple question about strings in Java. The following segment of simple code just concatenates two strings and then compares them with ==
.
As per my research, all the final String
are interned in Java. From one of the blog post:
So, if you really need to compare two String using == or != make sure you call String.intern() method before making comparison. Otherwise, always prefer String.equals(String) for String comparison.
So it means if you call String.intern()
you can compare two strings using ==
operator. But here String.intern()
is not necessary because in Java final String
are internally interned.
You can find more information String comparision using == operator and Javadoc for String.intern() method.
Also refer this Stackoverflow post for more information.