Tuesday, October 1, 2013

What is the difference between String == and .equals method in Java

It has been long time that I visited my blog to post any update. Today I'm going to explain the difference between string == operator and .equals method.

Before we start lets define what is string intern pool.String intern pool is a process of maintaining only one copy of distinct strings on heap

Basically, String in Java is a object not a primitive data type. When you declare any variable in java as a string without new operator is called string literal. String created with new operator is called a string object. When a string literal is declared in java, during the execution process the java runtime enviroment (JVM) checks the string intern pool to see if the current string exists in it, if so the java runtime environment assigns existing string literal address to the current string, if not the current string will be added to the string intern pool.

When a string object is created with new operator, a new string object is created on heap. Even if you try to create another string with the same content, a new memory location will be allocated for it.

Lets see them with the help of examples

String a = "abc";
String b = "abc";

If there is no string 'abc' in string intern pool when you run this piece of code, the string 'abc' will be added to string intern pool when the first line of code is executed by JVM.When the second line is executed, JVM checks the string intern pool to see if the string 'abc' exists. It exists in this case hence it just assigns address of a to b.

String c =  new String("abc");

The above line of code creates a new string object on heap. If you try to create another string with the same content like String d = new String("abc"); it will be a new object on heap even though the object with the same content exists on heap, thats what the new operator does.

When you use == operator to check if two strings are equal, it actually checks the address of the two strings, returns true if the address of the two strings is same else returns false.

When you use .equals method, it checks the content of the strings. If the content is same it will return true else returns false.

As per above description, see the output of below statements
System.out.println(a == b); returns true
System.out.println(a.equals(d)); return true
System.out.println(a == c); returns false
System.out.prinln(a.equals(c)); returns true