Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusion with equal method

Tags:

java

equals

Whenever I use equals() method with two different StringBuffer objects, I get the result as false, but when I use equals() method with two different String objects, I get the result as true. Why?

    String s=new String("434");
    String s1=new String("434");

    System.out.println(s.equals(s1));//true

   StringBuffer s=new StringBuffer("434");
   StringBuffer s1=new StringBuffer("434");

   System.out.println(s.equals(s1));//false
like image 351
Dusk Avatar asked May 18 '26 12:05

Dusk


2 Answers

StringBuffer does not override equals(). As such, Object.equals() is called, which compare the object identity (the memory address). String does override equals and compare the content.

like image 53
Thierry-Dimitri Roy Avatar answered May 21 '26 01:05

Thierry-Dimitri Roy


StringBuffer does not override Object#equals(), so you're experiencing reference identity-based checks rather than value-based checks. As these StringBuilder instances are distinct, each with different memory locations, the base Object#equals() implementation will always return false.

Here's the definition as of Java 6:

public boolean equals(Object obj) {
  return (this == obj);
}

See the problem?

like image 35
seh Avatar answered May 21 '26 01:05

seh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!