equals() vs == in Java

Java 8Object Oriented ProgrammingProgramming

To check the difference between equals() and ==, let us take three strings.

String str1 = "Test";
String str2 = new String(str1);
String str3 = "Demo";

Let us check them with equals()

System.out.println(str1 + " equals " + str2 + " ? " + str1.equals(str2));
System.out.println(str1 + " equals " + str3 + " ? " + str1.equals(str3));

Now, we will check them with ==

System.out.println(str1 + " == " + str2 + " ? " + (str1 == str2));
System.out.println(str1 + " == " + str3 + " ? " + (str1 == str3));

The following is the final example with output that differentiates them accordingly .

Example

 Live Demo

public class Demo {
    public static void main(String[] args) {
       String str1 = "Test";
       String str2 = new String(str1);
       String str3 = "Demo";
       System.out.println(str1 + " equals " + str2 + " ? " + str1.equals(str2));
       System.out.println(str1 + " == " + str2 + " ? " + (str1 == str2));
       System.out.println(str1 + " equals " + str3 + " ? " + str1.equals(str3));
       System.out.println(str1 + " == " + str3 + " ? " + (str1 == str3));
    }
}

Output

Test equals Test ? true
Test == Test ? false
Test equals Demo ? false
Test == Demo ? false
raja
Published on 12-Dec-2018 08:36:44
Advertisements