Difference Between == and .equals() Method in Java

Kasun Dissanayake
6 min readApr 2, 2022

--

In this article, we discuss all .equals() method and == operator in Java. You will get a deep understanding of these 2 concepts and their usages.

Let’s say you have two integers number1 and number2. Let's try to compare these two integers using the equals(“==”) operator. I am going to assign different values to the numbers first and get the output. Yeah, they are not equal what will be the output.

package EqualsandOperator;class Example{public static void main(String[] args) { int number1 = 3; int number2 = 5; if (number1 == number2) {     System.out.println("The numbers are equal"); }else{     System.out.println("The numbers are not equal"); } } }
The numbers are not equal output

They are not equal. Because the values of the two integers are different.

Now I am going to compare these variables using the .equals() method. Here I am going to assign the same value for both number1 and number2.

The numbers are equal output

Now they are equal. It is working because both values of the strings are the same.

This works perfectly for integers. But what happens if we use different kinds of variables in Java. Instead of using Integers let’s use some other kinds of primitive types like String. Let’s create string1 and string2 variables and assume the same value for both.

package EqualsandOperator;class Example{   public static void main(String[] args) {   String string1 = new String("same string");   String string2 = new String("same string"); if (string1 == string2) {   System.out.println("The strings are equal"); }else{   System.out.println("The strings are not equal");}}}

Now you can see the strings are not equal to the output. But we gave exactly the same strings value for both strings.

String are not equal output

The reason for this is that Java checks the underline memory location of those two Objects. When we use a new String(“string”), Java allocates a new memory location and then creates the variable string1 and points to that memory location. For the second string, the same thing happens. It creates another memory location string2 points to that second memory location. So now we can understand this will comparing both memory locations of those two objects. And of course, they are different that's why we get false and that output.

You may be asking why it works fine for int variables. In Java primitives like int, float, short, long, char, boolean, byte, and double they are referring to the actual values, not the memory locations where the object is stored. So for the above primitive types, this works fine.

Then how can we get the correct answer? Use .eqauls() method on your Objects. The String class offers this equals method. Inside the equals method, we can use the string which you want to compare.

if (string1.equals(string2)) {   System.out.println("The strings are equal");}else{   System.out.println("The strings are not equal");}

Now change the code and execute. You will get an output like this.

The Strings are equal output

equals() method in String Class

equals() Method. In Java, the String equals() method compares the two given strings based on the data/content of the string. If all the contents of both the strings are the same, it returns true. If all characters are not matched, then it returns false.

Basically, every other type you used in Java should offer the .equals() method. So you can compare one object of that class and another object of that class. For every library, you used like Strings, Collections, and everything offered in the main JAVA library have implemented equals() method for you to use.

Now I am creating my own class(Custom Class) called Car.java and I am going to compare two objects in that Class using the .equals method.

package EqualsandOperator;class Example{public static void main(String[] args) { Car myCar = new Car(); Car yourCar = new Car(); if (myCar.equals(yourCar)) {    System.out.println("The Cars are equal"); }else{    System.out.println("The Cars are not equal");}}}

According to the previous observation, we should get the output as “The Cars are equal”. Because when we use the .equals() method it will take the value of Objects instead of getting the references. But you can see, we will not get an output like “The Cars are equal”. We will get an output like this.

Custom objects are not equal output

The reason is the .equals() method hasn't been implemented yet in my Cars class. If we don't implement the equals method it will use the default method implementation of the equals method in the Object class(Parent of all other classes) in Java.

Object class equals method

So how can we implement the .equals() methods in our class? All need to do is write that method in your Car class. Add this method into your Car class and check the output you will get the correct output now.

public boolean equals(Object obj) { if (this == obj)    return true; if (obj == null)    return false; if (getClass() != obj.getClass())    return false; Car car = (Car) obj; if (this.color != car.color)    return false; if (this.model != car.model)    return false; if (this.price != car.price)    return false;return true;}
Custom Objects are equal output

What happens when we use the “==” operator with String literals

A string literal or anonymous string is a type of literal for the representation of a string value in the source code of a computer program.

String string1 = “same string”;

Now let's get the previous example and instead of using a new String, we can use String literals. Let's compare these string1 and string2 strings using the “==” operator. What will be the output?

String literals equal output

If we define two different string variables that refer to the same string literal java will just hold that string literal in one place in memory and both variables will point to that memory if you don't use the new String command.

This is called String Interning. String Interning is a method of storing only one copy of each distinct String Value, which must be immutable. By applying String. intern() on a couple of strings will ensure that all strings having the same contents share the same memory.

String Interning

So this is a kind of weird thing. Sometimes Strings “==” is working and sometimes it is not working. So just don't use “==” for anything except primitive types. In Strings and Custom, objects use the .equals() method for the comparison of strings and Objects.

I hope you got a basic understanding of these theories about the .equals() method and the “==” operator. We will meet in another tutorial.

Thank You!

--

--

Kasun Dissanayake

Senior Software Engineer at IFS R & D International || Former Software Engineer at Pearson Lanka || Former Associate Software Engineer at hSenid Mobile