- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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); } }
Advertisements