Java and equals operator

Difference between == and equals() method in Java? String Example

What is the difference between == and equals() method for comparing Objects in Java is one of the classical Interview Questions which appears now and then in many interviews? This question is mostly asked in conjunction with String because comparing String using == and equals() method returns different results. I have often seen along with other popular String questions like StringBuffer vs StringBuilder, Why String is final etc. Java is a pure object-oriented language and every object has one state and location in the memory and equals () and == are related to the state and location of the object, now in this article will try to understand this concept and the difference between == and equals method in Java.

What is the equals method and == operator in Java?

Both equals() method and the == operator are used to compare two objects in Java. == is an operator and equals() is method. But == operator compares reference or memory location of objects in the heap, whether they point to the same location or not.

Whenever we create an object using the operator new it will create a new memory location for that object. So we use the == operator to check memory location or address of two objects are the same or not.

When we talk about the equals() method the main purpose is to compare the state of two objects or the contents of the object. But there is one relationship between these two is the default implementation of the equals() method works like == means it will check the memory reference of the object if they point to the same location then two objects are equals and it is defined in the Object class.

As we know java.lang.Object class is the parent for every other object so default implementation is common for every object but if we want to override the method and want to give our own implementation for checking the equality of two objects we can do, and most of the Java classes have their own implementation for equals method where they check the contents of the object.

Читайте также:  Mat to image java

Btw, if you are not familiar with essential OOP concepts like overloading and overriding then you should first check these Java online courses o understand. That will help you to understand the difference between the equals() method in the Object class and the String class.

For example java.lang.String class overrides the equals() and hashcode method and in the overridden method, it will check that two string contains same value or character if yes then they are equals otherwise not equal.

Difference between == and equals method in Java

Now we know what equals method, how it works and What is equality operator (==), and How it compares objects, it’s time to compare them. Here is some worth noting difference between equals() method and == operator in Java:

1. First difference between them is, equals() is a method defined inside the java.lang.Object class, and == is one type of operator and you can compare both primitive and objects using equality operator in Java.

2. Second difference between equals and == operator is that == is used to check a reference or memory address of the objects whether they point to the same location or not, and the equals() method is used to compare the contents of the object e.g. in case of comparing String its characters, in case of Integer it’s their numeric values, etc.

You can define your own equals method for domain objects as per business rules e.g. two Employee objects are equal if their EmployeeId is the same.

3. Third difference between equals and the == operator is that You can not change the behavior of == operator but we can override the equals() method and define the criteria for the equality of the objects.

String s1= new String ( «hello» ) ;
String s2= new String ( «hello» ) ;

Here we have created two strings s1 and s2 now will use the == and equals () method to compare these two String to check whether they are equal or not.

First, we use the equality operator == for comparison which only returns true if both reference variables are pointing to the same object.

if ( s1==s2 ) <
System. out . printlln ( «s1==s2 is TRUE» ) ;
> else <
System. out . println ( «s1==s2 is FALSE» ) ;
>

Читайте также:  Treeset sorting in java

The output of this comparison is FALSE because we have created two objects which have a different location in the heap so == compare their reference or address location and return false. Now if we use the equals method to check their equivalence what will be the output

if ( s1. equals ( s2 )) <
System. out . println ( «s1.equals(s2) is TRUE» ) ;
> else <
System. out . println ( «s1.equals(s2) is FALSE» ) ;
>

The output of this comparison is TRUE because of java.lang.String class has already overridden the equals() method of Object class and check that contents are the same or not because both have the same value hello so they are equal according to String class equals() method.

A picture is worth thousands of words and here is a picture that explains whatever I have said in the above paragraph about equals() vs == operator in the case of String in Java:

Difference between == and equals() method in Java - String Object

Point to remember:

If you have not overridden the equals() method in a user-defined object, it will only compare the reference or memory address as defined in the default equals() method of java.lang.Object class and return true only if both reference variable points to the same object.

So in a user-defined class, both equals() and == operator behave similarly but that may not be logically correct and that’s why we should always define the equivalence criteria for custom or domain objects.

That’s all on the difference between the equals() method and == operator in Java. Both can compare objects for equality but equals() is used for logical and business logic comparison while == mostly for object reference comparison in Java.

Thanks for reading this article so far. If you like this core Java interview question and my explanation then please share it with your friends and colleagues. If you have any doubt or feedback then please drop a note.

Источник

Equality, Relational, and Conditional Operators

The equality and relational operators determine if one operand is greater than, less than, equal to, or not equal to another operand. The majority of these operators will probably look familiar to you as well. Keep in mind that you must use » == «, not » = «, when testing if two primitive values are equal.

== equal to != not equal to > greater than >= greater than or equal to < less than 

The following program, ComparisonDemo , tests the comparison operators:

class ComparisonDemo < public static void main(String[] args)< int value1 = 1; int value2 = 2; if(value1 == value2) System.out.println("value1 == value2"); if(value1 != value2) System.out.println("value1 != value2"); if(value1 >value2) System.out.println("value1 > value2"); if(value1 < value2) System.out.println("value1 < value2"); if(value1 >

The Conditional Operators

The && and || operators perform Conditional-AND and Conditional-OR operations on two boolean expressions. These operators exhibit "short-circuiting" behavior, which means that the second operand is evaluated only if needed.

&& Conditional-AND || Conditional-OR

The following program, ConditionalDemo1 , tests these operators:

Another conditional operator is ?: , which can be thought of as shorthand for an if-then-else statement (discussed in the Control Flow Statements section of this lesson). This operator is also known as the ternary operator because it uses three operands. In the following example, this operator should be read as: "If someCondition is true , assign the value of value1 to result . Otherwise, assign the value of value2 to result ."

The following program, ConditionalDemo2 , tests the ?: operator:

Because someCondition is true, this program prints "1" to the screen. Use the ?: operator instead of an if-then-else statement if it makes your code more readable; for example, when the expressions are compact and without side-effects (such as assignments).

The Type Comparison Operator instanceof

The instanceof operator compares an object to a specified type. You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.

The following program, InstanceofDemo , defines a parent class (named Parent ), a simple interface (named MyInterface ), and a child class (named Child ) that inherits from the parent and implements the interface.

class InstanceofDemo < public static void main(String[] args) < Parent obj1 = new Parent(); Parent obj2 = new Child(); System.out.println("obj1 instanceof Parent: " + (obj1 instanceof Parent)); System.out.println("obj1 instanceof Child: " + (obj1 instanceof Child)); System.out.println("obj1 instanceof MyInterface: " + (obj1 instanceof MyInterface)); System.out.println("obj2 instanceof Parent: " + (obj2 instanceof Parent)); System.out.println("obj2 instanceof Child: " + (obj2 instanceof Child)); System.out.println("obj2 instanceof MyInterface: " + (obj2 instanceof MyInterface)); >> class Parent <> class Child extends Parent implements MyInterface <> interface MyInterface <>
obj1 instanceof Parent: true obj1 instanceof Child: false obj1 instanceof MyInterface: false obj2 instanceof Parent: true obj2 instanceof Child: true obj2 instanceof MyInterface: true

When using the instanceof operator, keep in mind that null is not an instance of anything.

Previous page: Assignment, Arithmetic, and Unary Operators
Next page: Bitwise and Bit Shift Operators

Источник

Оцените статью