Difference Between String and StringBuffer Class in Java


In this post, we will understand the difference between String and StringBuffer class in Java.

String

  • It is an immutable class.

  • This means changes can’t be made to elements of the class.

  • It is slow.

  • It consumes less memory when strings are concatenated.

  • This is because every time, a new instance is created.

  • It overrides the equals() method of Object class.

  • Hence, the ‘equals’ method can be used to compare two strings.

Following is an example of the String class −

Example

public class StringDemo {
   public static void main(String args[]) {
      String palindrome = "Dot saw I was Tod";
      int len = palindrome.length();
      System.out.println( "String Length is : " + len );
   }
}

StringBuffer

  • It is a mutable class.

  • This means changes can be made to the elements in this class.

  • It is fast.

  • It uses less memory when strings are concatenated.

  • It class doesn't override the equals() method of Object class.

Following is an example of the StringBuffer class −

Example

public class Demo {
   public static void main(String args[]) {
      StringBuffer sBuffer = new StringBuffer("test");
      sBuffer.append(" String Buffer");
      System.out.println(sBuffer);
   }
}

Updated on: 24-Mar-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements