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

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
The numbers are equal output
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");}}}
String are not equal output
if (string1.equals(string2)) {   System.out.println("The strings are equal");}else{   System.out.println("The strings are not equal");}
The Strings are equal output

equals() method in String Class

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");}}}
Custom objects are not equal output
Object class equals method
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

String literals equal output
String Interning

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Kasun Dissanayake

Kasun Dissanayake

1.3K Followers

Software Engineer at IFS R & D International (Pvt) Ltd || Former Software Engineer at Pearson Lanka || Former Associate Software Engineer at hSenid Mobile