Consider the following codes in 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)); } } |
false
// This program prints true class GFG { public static void main(String[] args) { String s1 = "GFG"; String s2 = "GFG"; System.out.println(s1.equals(s2)); } } |
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 second 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.
// 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)); } } |
false
// 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)); } } |
true
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- String vs StringBuilder vs StringBuffer in Java
- Sorting collection of String and StringBuffer in Java
- Matcher appendReplacement(StringBuffer, String) method in Java with Examples
- Collator equals(String, String) method in Java with Example
- StringBuffer insert() in Java
- StringBuffer class in Java
- StringBuffer setLength() in Java with Examples
- StringBuffer subSequence() in Java with Examples
- Difference Between StringBuffer and StringBuilder in Java
- A Java Random and StringBuffer Puzzle
- StringBuffer indexOf() method in Java with Examples
- StringBuffer codePointBefore() method in Java with Examples
- StringBuffer trimToSize() method in Java with Examples
- StringBuffer append() Method in Java with Examples
- StringBuffer substring() method in Java with Examples
- StringBuffer codePointCount() method in Java with Examples
- StringBuffer lastIndexOf() method in Java with Examples
- StringBuffer replace() Method in Java with Examples
- StringBuffer setCharAt() method in Java with Examples
- StringBuffer reverse() Method in Java with Examples
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

