Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking For Equal Instances of 2 Different (Included Example)

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!");
        }
    }
}
like image 690
Brent Avatar asked Sep 07 '10 03:09

Brent


2 Answers

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.

like image 167
jjnguy Avatar answered Sep 24 '22 07:09

jjnguy


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.

like image 21
Leniel Maccaferri Avatar answered Sep 24 '22 07:09

Leniel Maccaferri