abhisays

Last Updated: September 27, 2014  732 views

What is difference between == and equals() in Java?

in: Tips and Tricks

Java ProgrammerNormally in almost every second Java-J2EE interview, interviewers ask this question. This question confuses a lot of Java programmers. In one line you can answer this question. == compares the reference value of string object whereas equals() method is present in the java.lang.Object class. This method compares content of the string object. The equals() method is inherited from Object class and is overridden to perform the deep comparison means comparing the characters of two strings. It returns true if the two strings contain identical characters in the same order. Let us take one example.

public class StringComp {
public static void main(String[] args) {
String str1 = “Hello World!”; //adds the string Hello World! to the string pool.
String str2 = “Hello World!”;
String str3 = new String (“Hello World!”);

if (str1.equals(str2)) {
System.out.println(“str1 and str2 refer to identical strings.”);
} else {
System.out.println(“str1 and str2 refer to non-identical strings.”);
}
if (str1 == str2) {
System.out.println(“str1 and str2 refer to the same string.”);
} else {
System.out.println(“str1 and str2 refer to different strings.”);
}
if (str1.equals(str3)) {
System.out.println(“str1 and str3 refer to identical strings.”);
} else {
System.out.println(“str1 and str3 refer to non-identical strings.”);
}
if (str1 == str3) {
System.out.println(“str1 and str3 refer to the same string.”);
} else {
System.out.println(“str1 and str3 refer to different strings.”);
}

}
}

Output of this program ::

After the execution of String str1 = “Hello World!”; the JVM adds the string “Hello World!” to the string pool and on next line of the code, it encounters String str2 =”Hello World!”; in this case the JVM already knows that this string is already there in pool, so it does not create a new string. So both str1 and str2 points to the same string means they have same references. However, str3 is created at runtime so it refers to different string.

Before running the program, guess the output and then run. Always keep in mind, == compares the reference value of string object whereas equals() compares content of the string object.