contentEquals Java

Use equals() to compare two strings but to compare a string with StringBuffer use contentEquals ().

Following both are the methods of String class returning boolean values.

public boolean contentEquals(java.lang.StringBuffer);
public boolean contentEquals(java.lang.CharSequence);
The next code explains contentEquals Java


public class Demo
  public static void main(String args[])
    String str1 = "hello";    
    String str2 = "hello";

    StringBuffer sb1 = new StringBuffer("hello");
    StringBuffer sb2 = new StringBuffer("world");

    boolean b1 = str1.equals(str2);        // works nice and returns true

    boolean b2 = str1.equals(sb1);         // works nice and returns false

    boolean b3 = str1.contentEquals(sb1);  // works nice and returns true

    boolean b4 = str1.contentEquals(sb2);  // works nice and returns false

    boolean b5 = str1.contentEquals(str2);  // works nice and returns true


The parameters of contentEquals () are StringBuffer and String (charSequence). equals() is used to compare two strings and contentEquals() is used to compare the contents of String and StringBuffer. Observe the above code and is self-explanatory.

For programming traps in using equals() and == with strings: String – Immutable Nature – Comparison

================Extra Reading on Inner classes=================

Because inner classes usage is growing slowly, they are discussed more elaborately here. Android (Java based Mobile OS developed by Google) uses inner classes very extensively, infact anonymous inner classes are passed as parameters to methods.

In this series following combinations are discussed.

1. Java Nested Classes
2. Static Nested Classes
3. Nested Interfaces
4. Interface inside Interface
5. Nested Interface within Class
6. Class inside Interface

1 thought on “contentEquals Java”

  1. sir , i made a prog
    public class Test2{
    public static void main(String[] args){
    Test t = new Test();
    Object o1 = new Object();
    Object o2 = new Object();

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

    Integer i = new Integer(t.a);
    System.out.println(“using string objects “);
    System.out.print(” == method : “);
    if (s1==s2){
    System.out.println(“equal memory”+t.a+” ” +t.b);
    System.out.println(“diffent memory”);

    System.out.print(” using equals method : “);
    if (s1.equals(s2)){
    System.out.println(“equal memory” +t.a+” ” +t.b);
    System.out.println(“diffent memory”);

    System.out.println(“2nd set *************************** “);
    System.out.print(“using equal method :”);
    if (s1.equals(o1)){
    System.out.println(“equal memory” +t.a+” ” +t.b);
    System.out.println(“diffent memory”);

    other java class is
    public class Test {
    int a =20;
    int b =20;


    in second set of code why it is not printing equal memory ??

Leave a Comment

Your email address will not be published.