- 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
Why should we use a StringBuffer instead of a String in Java?
- A StringBuffer is a thread-safe, mutable sequence of characters.
- Unlike a String class (immutable), the StringBuffer class is mutable. That is, we can change the contents of a StringBuffer object.
- When we modify a string of StringBuffer class, we are not creating a new String object, but rather operating directly on the original string itself.
- For this reason, the StringBuffer class offers a different set of methods than the String class, all of which operate directly on the buffer that contains the string.
A StringBuffer can be defined simply by the use of the new operator and bypassing the string value inside a StringBuffer constructor.
Example
class StringBufferDemo{ public static void main(String arg[]){ StringBuffer sb = new StringBuffer(); sb.append("Java Tutorials Point"); System.out.println(sb); } }
In the above program, we initially created an instance of a StringBuffer class and appended "Java Tutorials Point" to the StringBuffer class using append() method.
Output
Java Tutorials Point
Advertisements