I use the == in the code below and prints out “Equals!”, why? Can someone explain why these two different strings a and b are equal?
public class test
{
public static void main()
{
String a = "boy";
String b = "boy";
if(a == b)
{
System.out.println("Equals!");
}
else
{
System.out.println("Does not equal!");
}
}
}
This is due to
Stringinterning.Java (The JVM) keeps a collection of
Stringliterals that is uses to save memory. So, whenever you create aStringlike so:Java ‘interns’ the string. However, if you create the
Stringlike so:Java will not automatically intern the
String. If you created your strings this way, your code would produce different results.A quick Google search reveals lots of good resources regarding
Stringinterning.