The Wayback Machine - https://web.archive.org/web/20241114041440/https://www.geeksforgeeks.org/difference-between-and-equals-method-in-java/
Open In App

Difference between comparing String using == and .equals() method in Java

Last Updated : 04 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Both the equals() method and the == operator are used to compare two objects in Java.

The Java string equals() method, compares two strings and returns true if all characters match in both strings, else returns false.

The == operator compares the reference or memory location of objects in a 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.

In general, both equals() and “==” operators in Java are used to compare objects to check equality, but here are some of the differences between the two: 

  1. The main difference between the .equals() method and the == operator is that one is a method, and the other is the operator.
  2. We can use == operators for reference comparison (address comparison) and .equals() method for content comparison. In simple words, == checks if both objects point to the same memory location whereas .equals() evaluates to the comparison of values in the objects.
  3. If a class does not override the equals method, then by default, it uses the equals(Object o) method of the closest parent class that has overridden this method. **See Why to Override equals(Object) and hashCode() method? in detail.

Understanding the difference between == and .equals() when comparing strings is key to avoiding bugs in your code. To explore more about string handling and comparisons, the Java Programming Course provides practical examples and best practices.

Example:

String equals() method and == operator in Java.

Java
// Java program to understand 
// the concept of == operator

public class Test {
    public static void main(String[] args)
    {
        String s1 = "HELLO";
        String s2 = "HELLO";
        String s3 =  new String("HELLO");

        System.out.println(s1 == s2); // true
        System.out.println(s1 == s3); // false
        System.out.println(s1.equals(s2)); // true
        System.out.println(s1.equals(s3)); // true
    }
}

Output
true
false
true
true

Explanation: Here, we create two objects, namely s1 and s2. 

  • Both s1 and s2 refer to the same objects.
  • When we use the == operator for s1 and s2 comparison, the result is true as both have the same addresses in the string constant pool.
  • Using equals, the result is true because it’s only comparing the values given in s1 and s2.

 Java String Pool

s1 = “HELLO”

s2 = “HELLO”

Java Heap

s3 = “HELLO”

Let us understand both the operators in detail:

Equality operator(==)

We can apply equality operators for every primitive type, including the boolean type. We can also apply equality operators for object types. 

Example:

== operator in Java.

Java
// Java program to illustrate 
// == operator for compatible data
// types

class Test {
    public static void main(String[] args)
    {
        // integer-type
        System.out.println(10 == 20);

        // char-type
        System.out.println('a' == 'b');

        // char and double type
        System.out.println('a' == 97.0);

        // boolean type
        System.out.println(true == true);
    }
}

Output
false
false
true
true

If we apply == for object types then, there should be compatibility between argument types (either child to parent or parent to child or same type). Otherwise, we will get a compile-time error. 

Example:

Java
// Java program to illustrate 
// == operator for incompatible data types

class Test {
    public static void main(String[] args)
    {
        Thread t = new Thread();
        Object o = new Object();
        String s = new String("GEEKS");

        System.out.println(t == o);
        System.out.println(o == s);

       // Uncomment to see error 
       System.out.println(t==s);
    }
}

Output: 

false
false
// error: incomparable types: Thread and String

Java String 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 strings are the same, it returns true. If all characters are not matched, then it returns false.

Syntax:

Syntax: public boolean equals(Object anotherObject)

Parameter:

  • anotherObject- String to be compared

Returns:

  • Boolean value:
    • true- If strings are equal
    • false- if strings are not equal

Example:

String equals() method in Java

Java
public class Test {
    public static void main(String[] args)
    {
        Thread t1 = new Thread();
        Thread t2 = new Thread();
        Thread t3 = t1;

        String s1 = new String("GEEKS");
        String s2 = new String("GEEKS");

        System.out.println(t1 == t3);
        System.out.println(t1 == t2);
        System.out.println(s1 == s2);

        System.out.println(t1.equals(t2));
        System.out.println(s1.equals(s2));
    }
}

Output:

true
false
false
false
true

Explanation: Here, we are using the .equals method to check whether two objects contain the same data or not. 

  • In the above example, we create 3 Thread objects and 2 String objects.
  • In the first comparison, we check whether t1 == t3 or not. As we know both t1 and t3 point to the same object. That’s why it returns true.
  • In the second comparison, we are using the operator “==” for comparing the String Objects and not the contents of the objects. Here, both the objects are different, and hence the outcome of this comparison is “False.”
  • When we are comparing 2 String objects by the equals() operator, then we are checking that is both objects contain the same data or not.
  • Both the objects contain the same String, i.e., GEEKS. That’s why it returns true.

Also Read:

Conclusion

Java string equals() method and == operator are both used to compare strings in Java. In this tutorial we have covered the ==operator and String equals() method in Java with examples.

Read More String Methods in Java

Difference between == and .equals() method- FAQs

1. What is the difference between str1 == str2 and str1 equals str2?

In Java, str1==str2 will return true if str1 and str2 are strings with the same content. This is because strings with the same content are stored at the same location.

str1.equals(str2) will return true if str1 and str 2 are different string objects, but have same content.

2. What is the difference between == and equals in string comparison?

The string equals() method compares two strings and returns true if all characters match in both strings, else returns false.

The == operator compares the reference or memory location of objects in a heap, whether they point to the same location or not.

3. What are the rules of equals() method?

  1. Reflexivity: For any object x, x.equals(x) should always return true. 
  2. Symmetry: If x.equals(y) returns true, then y.equals(x) must also return true.
  3. Transitivity: If x.equals(y) and y.equals(z) are both true, then x.equals(z) must also be true. 
  4. Consistency: Multiple invocations of x.equals(y) should return the same result.
  5. Non-nullity: The equals() method should never return true when compared to null.


Similar Reads

Collator equals(String, String) method in Java with Example
The equals() method of java.text.Collator class is used to check if both strings are identical or not. Syntax: public boolean equals(String source, String target) Parameter: This method takes two strings between which comparison is going to take place. Return Value: if both strings are equal to each other then it will return true otherwise false. B
2 min read
Method Class | equals() Method in Java
The java.lang.reflect.Method.equals(Object obj) method of Method class compares this Method Object against the specified object as parameter to equal(object obj) method. This method returns true if the Method object is the same as the passed object. Two Methods are the same if they were declared by the same class and have the same name and formal p
3 min read
Comparing enum members in Java
Prerequisite : enum in Java, == vs equals In Java, enum is a special Java type used to define collections of constants. More precisely, a Java enum type is a special kind of Java class. An enum can contain constants, methods etc. enum can be defined as a group of named constant. There are two ways for making comparison of enum members : By using ==
3 min read
Comparing Streams to Loops in Java
A stream is an ordered pipeline of aggregate operations(filter(), map(), forEach(), and collect()) that process a (conceptually unbounded) sequence of elements. A stream pipeline consists of a source, followed by zero or more intermediate operations; and a terminal operation. An aggregate operation performs a function. Ideally, a function's output
7 min read
equals() on String and StringBuffer objects in Java
Consider the following codes in java: Java Code // This program prints false class GFG { public static void main(String[] args) { StringBuffer sb1 = new StringBuffer("GFG"); StringBuffer sb2 = new StringBuffer("GFG"); System.out.println(sb1.equals(sb2)); } } Output: false Java Code // This program prints true class GFG { public
2 min read
Java.util.Arrays.equals() in Java with Examples
Today we are going to discuss the simplest way to check whether two arrays are equal or not. Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. In other words, two arrays are equal if they contain the same elements in the same order. Also, two arra
4 min read
Longest Subsequence with difference between characters equals to K
Given a string S consisting of lowercase letters. Find the longest subsequence of S such that the difference between the maximum and minimum occurring characters in the subsequence is exactly K. Examples: Input: S = 'abcdeg' and K = 4Output: abcde Input: S = 'daaaabbbadddddeeee', K = 1Output: ddddddeeee Approach: This can be solved with the followi
9 min read
Calendar.equals() method in Java
java.util.Calendar.equals() is a method in Calendar class of java.util package. The method compares this Calendar to the specified Object.The method returns true if this object is equal to object. If this is not the case, i.e, if there is any difference in the parameters between the two Calendars, then false is returned. Syntax : public boolean equ
2 min read
Java Long equals() method with Examples
The java.lang.Long.equals() is a built-in function in java that compares this object to the specified object. The result is true if and only if the argument is not null and is a Long object that contains the same long value as this object. It returns false if both the objects are not same. In all other cases, compareTo method should be preferred. S
3 min read
Character.equals() method in Java with examples
The java.lang.Character.equals() is a function in Java which compares this object against the specified object. If the argument is not null then the result is true and is a Character object that represents the same char value as this object. Syntax: public boolean equals(Object obj) Parameters: The function accepts a single parameter obj which spec
2 min read
Double.equals() Method in Java with Examples
The java.lang.Double.equals() is a built-in function in java that compares this object to the specified object. The result is true if and only if the argument is not null and is a Double object that contains the same double value as this object. It returns false if both the objects are not same. In all other cases, compareTo method should be prefer
2 min read
MathContext equals() Method in Java
The java.math.MathContext.equals() is an in-built function in Java which checks for equality between this MathContext object with the object passed as parameter to the function. The function returns true if the context settings of both the aforementioned objects are same. Syntax : public boolean equals(Object obj) Parameters : The function accepts
2 min read
BigDecimal equals() Method in Java
The java.math.BigDecimal.equals() method checks for equality of a BigDecimal value with the object passed. This method considers two BigDecimal objects equal if only if they are equal in value and scale. Syntax: public boolean equals(Object obj) Parameters: This function accepts an Object obj as a mandatory parameter for comparison with this BigDec
2 min read
IdentityHashMap equals() Method in Java
The java.util.IdentityHashMap.equals() method in Java is used to check for equality between two maps. It verifies whether the elements of one map passed as a parameter is equal to the elements of this map or not. Syntax: ihashmap1.equals(ihashmap2) Parameters: The method accepts one parameter ihashmap2 of identity hash map type and refers to the ma
2 min read
GregorianCalendar equals() Method in Java
The java.util.GregorianCalendar.equals() method is an in-built function in Java which checks for equality between this GregorianCalendar instance and the Object passed as parameter to the function. It returns true only if the specified Object is a GregorianCalendar object with same time value (millisecond offset from the Epoch) as this GregorianCal
3 min read
BigInteger equals() Method in Java
The java.math.BigInteger.equals(Object x) method compares this BigInteger with the object passed as the parameter and returns true in both are equal in value else it returns false. Syntax: public boolean equals(Object x) Parameter: This method accepts a single mandatory parameter x which is the Object to which BigInteger Object is to be compared. R
3 min read
Vector equals() Method in Java
The java.util.vector.equals(Object obj) method of Vector class in Java is used verify the equality of an Object with a vector and compare them. The list returns true only if both Vector contains same elements with same order. Syntax: first_vector.equals(second_vector) Parameters: This method accepts a mandatory parameter second_vector which refers
2 min read
Java 8 Clock equals() Method with Examples
Java Clock class is part of Date Time API, java.time.Clock, of Java. The Java Date Time API was added from Java version 8.The equals() method of java.time.Clock class checks if two Clock objects are equal or not. If clocks are equal then it returns true, else it returns false. This equals method of clock class overrides this Object.equals(java.lang
3 min read
ConcurrentSkipListSet equals() method in Java
The equals() method of java.util.concurrent.ConcurrentSkipListSet is an inbuilt function in Java which compares the specified object with this set for equality. It returns True if the specified object is also a set. The two sets will said to be equal if they satisfies all of the conditions stated below: The two sets have the same size. Every member
3 min read
FloatBuffer equals() method in Java with Examples
The equals() method of java.nio.FloatBuffer Class is used to check whether or not the given buffer is equal to another object. Two float buffers are equal if, and only if, They have the same element type, They have the same number of remaining elements, and The two sequences of remaining elements, considered independently of their starting position
4 min read
LongBuffer equals() method in Java
The equals() method of java.nio.LongBuffer Class is used to check whether or not the given buffer is equal to another object. Two Long buffers are equal if, and only if, They have the same element type, They have the same number of remaining elements, and The two sequences of remaining elements, considered independently of their starting positions,
4 min read
ShortBuffer equals() method in Java with Examples
The equals() method of java.nio.ShortBuffer Class is used to check whether or not the given buffer is equal to another object. Two short buffers are equal if, and only if, They have the same element type, They have the same number of remaining elements, and The two sequences of remaining elements, considered independently of their starting position
3 min read
DoubleBuffer equals() method in Java with Examples
The equals() method of java.nio.DoubleBuffer Class is used to check whether or not the given buffer is equal to another object. Two double buffers are equal if, and only if, They have the same element type, They have the same number of remaining elements, and The two sequences of remaining elements, considered independently of their starting positi
3 min read
CharBuffer equals() method in Java
The equals() method of java.nio.CharBuffer Class is used to check whether or not the given buffer is equal to another object. Two char buffers are equal if, and only if, They have the same element type, They have the same number of remaining elements, and The two sequences of remaining elements, considered independently of their starting positions,
4 min read
ByteBuffer equals() method in Java with Examples
The equals() method of java.nio.ByteBuffer class is used to check whether or not the given buffer is equal to another object. Two byte buffers are equal if, and only if, They have the same element type, They have the same number of remaining elements, and The two sequences of remaining elements, considered independently of their starting positions,
3 min read
Boolean equals() method in Java with examples
The equals() method of Boolean class is a built in method of Java which is used check equality of two Boolean object. Syntax: BooleanObject.equals(Object ob) Parameter: It take a parameter ob of type Object as input which is the instance to be compared. Return Type: The return type is boolean. It returns true if the specified Object 'ob' has same v
2 min read
Byte equals() method in Java with examples
The equals() method of Byte class is a built in method in Java which is used to compare the equality given Object with the instance of Byte invoking the equals() method. Syntax ByteObject.equals(Object a) Parameters: It takes an Object type object a as input which is to be compared with the instance of the Byte object calling the equals method. Ret
2 min read
Short equals() method in Java with Examples
The equals() method of Short class is a built in method in Java which is used to compare the equality given Object with the instance of Short invoking the equals() method. Syntax ShortObject.equals(Object a) Parameters: It takes an Object type object a as input which is to be compared with the instance of the Short object calling the equals method.
2 min read
CopyOnWriteArraySet equals() method in Java
The equals(Object O) method of CopyOnWriteArraySet compares the specified object with this set for equality. Returns true if the specified object is the same object as this object, or if it is also a Set and the elements returned by an iterator over the specified set are the same as the elements returned by an iterator over this set. More formally,
2 min read
LocalDateTime equals() method in Java with Examples
The equals() method of LocalDateTime class in Java checks if this date-time is equal to another date-time. This other date-time is passed as the parameter. This method returns a boolean value showing the same. Syntax: public boolean equals(Object date2) Parameter: This method accepts a parameter date2 which checks if this date-time is equal to anot
2 min read
three90RightbarBannerImg