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 String
interning.
Java (The JVM) keeps a collection of String
literals that is uses to save memory. So, whenever you create a String
like so:
String s = "String";
Java 'interns' the string. However, if you create the String
like so:
String s = new String("String");
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 String
interning.
This article will explain it in details:
What is the difference between == and equals() in Java?
After the execution of String a = “boy”; the JVM adds the string “boy” to the string pool and on the next line of the code, it encounters String b = ”boy” again; in this case the JVM already knows that this string is already there in the pool, so it does not create a new string. So both strings a and b point to the same string what means they point to the same reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With