Saturday, September 6, 2025
HomeLanguagesJavaequals() on String and StringBuffer objects in Java

equals() on String and StringBuffer objects in Java

Consider the following codes in java: 
 

Java




// 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




// This program prints true
class GFG {
 
  public static void main(String[] args) {
    String s1 = "GFG";
    String s2 = "GFG";
    System.out.println(s1.equals(s2));
  }
}


Output: 

true

 

The output is false for the first example and true for the second example. In second example, parameter to equals() belongs String class, while in first example it to StringBuffer class. When an object of String is passed, the strings are compared. But when object of StringBuffer is passed references are compared because StringBuffer does not override equals method of Object class.
For example, following first program prints false and second prints true.
 

Java




// This program prints false
class GFG {
 
  public static void main(String[] args) {
    String s1 = "GFG";
    StringBuffer sb1 = new StringBuffer("GFG");
    System.out.println(s1.equals(sb1));
  }
}


Output: 

false

 

Java




// This program prints true
class GFG {
 
  public static void main(String[] args) {
    String s1 = "GFG";
    StringBuffer sb1 = new StringBuffer("GFG");
    String s2 = sb1.toString();
    System.out.println(s1.equals(s2));
  }
}


Output: 

true

 

RELATED ARTICLES

Most Popular

Dominic
32270 POSTS0 COMMENTS
Milvus
82 POSTS0 COMMENTS
Nango Kala
6639 POSTS0 COMMENTS
Nicole Veronica
11803 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11869 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7029 POSTS0 COMMENTS
Thapelo Manthata
6705 POSTS0 COMMENTS
Umr Jansen
6721 POSTS0 COMMENTS