BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Difference between String and StringBuffer

Last Updated: June 9, 2024 by Chaitanya Singh | Filed Under: java

In this article, we will discuss the difference between String and StringBuffer. Both of these classes used to handle sequence of characters. However they are different in certain areas such as mutability, performance, and thread-safety. Let’s discuss these differences with examples.

String

Immutability: String objects are immutable. This means that once a String object is created, its value cannot be changed. If any changes are made in a String a new String object is created.

String str1 = "Hello";
String str2 = str1.concat(", World!"); // str2 is a new String object

Performance: As we now know that String is immutable, concatenation operations create new String objects, this can cause significant performance overhead.

Usage: Strings are mostly used in scenarios where you do not require to change frequently.

Thread Safety: String is inherently thread-safe because it is immutable.

StringBuffer

Mutability: StringBuffer objects are mutable. This means when you change the value of StringBuffer objects, it doesn’t create new objects.

StringBuffer sb = new StringBuffer("Hello");
sb.append(", World!"); // sb is modified directly

Performance: StringBuffer is more efficient than String as any modification doesn’t create new objects. This is generally useful in scenarios where frequent changes are required.

Usage: StringBuffer is generally useful in scenarios where frequent changes are required.

Thread Safety: StringBuffer is thread-safe because the methods of StringBuffer class are synchronized. This makes it safe to use in multi-threaded environments.

String vs StringBuffer Example Comparison

An example to demonstrate difference in performance and usage:

Using String

public class StringExample {
public static void main(String[] args) {
String str = "Text";
for (int i = 0; i < 100; i++) {
str += " Text"; // Each iteration creates a new String object
}
System.out.println(str);
}
}

Using StringBuffer

public class StringBufferExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Text");
for (int i = 0; i < 100; i++) {
sb.append(" Text"); // Modifies the same StringBuffer object
}
System.out.println(sb.toString());
}
}

Key Points

  • Memory Efficiency: String is less memory efficient as any change creates new String object. StringBuffer is more memory efficient in such scenarios.
  • Thread Safety: String and StringBuffer are both thread-safe, however the reason for thread-safety is different in both cases. String is thread-safe because they are immutable, whereas StringBuffer is thread-safe because its methods are synchronized.
  • Usage:
    • Use String when changes to string are not so frequent.
    • Use StringBuffer when you need to make frequent changes to the string.

Top Related Articles:

  1. OOPs in Java: Encapsulation, Inheritance, Polymorphism, Abstraction
  2. Java StringBuilder offsetByCodePoints()
  3. How to take String Input in Java
  4. Java StringBuffer class With Examples
  5. Java Math.nextAfter() Method

Tags: Java-Strings, StringBuffer

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap