A Complete Guide to String, StringBuffer and StringBuilder in Java

    A Complete Guide to String, StringBuffer and StringBuilder in Java

    This article explores Strings in Java, focusing on immutability, memory management, and performance. It also compares String, StringBuilder, and StringBuffer, highlighting their key differences in mutability and thread safety.

    default profile

    Shreya Adak

    February 14, 2025

    6 min read

    Introduction:#

    String is a sequence of characters. In Java, the String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class. Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared.

    For example: String str = "abc";

    Is equivalent to:

    char data[] = {'a', 'b', 'c'};

    String str1 = new String(data);

    String Creation and Initialization: How to create and store Java String#

    There are two main ways to create and initialize a string:

    1. Using String Literals (Static Memory)
    2. Using the new Keyword (Heap Memory)

    1. Using String Literals:#

    Syntax: <String Class Type> <Obj or Variable name> = "<Variable value>";

    String Literal is any sequence of characters enclosed within " " double quotes. It is stored inside the String Pool (Static Memory).

    Examples: String str = "abc";

    Advantages of String Literals:#

    • Memory optimization due to String Pool.
    • Strings are shared, avoiding unnecessary object creation.

    2. Using the new Keyword:#

    Syntax: <String Class Type> <Obj or Variable name> = <'new' keyword> <String Constructor>;

    New objects are created by JVM for using of new keyword. It is stored inside the Heap memory.

    Examples: String str2 = new String("Hello, World!");

    Disadvantages of Using new Keyword:#

    • More memory consumption as each new call creates a separate object.
    • Less efficient compared to String literals when dealing with frequent string operations.

    String Pool and Interning: Memory Allocations:#

    • What is the String Pool?
      • The String Pool is a special memory area inside the Heap that stores string literals ("Hello", "Java", etc.).
      • It helps save memory by reusing existing string objects instead of creating new ones.
    • How Strings Are Stored in the Pool?
      • When a string literal (String s = "Java";) is created, Java checks the pool:
        • If it exists, the reference is reused.
        • If it doesn’t exist, a new object is added to the pool.
      • Strings created using new String("Java") are stored outside the pool in the Heap.

    Memory Efficiency

    • Advantage: Saves memory by avoiding duplicate string objects.
    • Best Practice: Use string literals ("text") instead of new String("text").

    String Immutability: Why are Strings immutable?#

    Immutable is a state/value of an object that can not be changed after creation. You can't change its value once you create any String object. That’s why Java Strings are immutable. Immutability provides security, memory efficiency, and thread safety. Performance benefits include hashcode caching and memory optimization in the String Pool.

    public class StringInJava { public static void main(String[] args) { String str = "abc"; str.concat("def"); System.out.println(str); //output "abd" } }

    Output:

    String output

    Why Are Strings Immutable?#

    • String Pool Optimization: Enables memory reuse, reducing redundant object creation.
    • Security: Prevents unauthorized modification in sensitive operations (e.g., passwords, URLs).
    • Thread Safety: Multiple threads can share String objects safely without synchronization.
    • Performance Boost: Hashcode caching improves efficiency in HashMap and HashSet.
    • Prevents Unintentional Modifications: Ensures predictable behavior when used across different references.

    Common String Methods:#

    You can visit Oracle’s official documentary https://docs.oracle.com/javase/8/docs/api/java/lang/String.html

    String Comparison:#

    equals(Object obj): This is a case-sensitive comparison. If two string contents are equal then return true, otherwise return false.

    public class StringInJava { public static void main(String[] args) { String str1 = "abc"; String str2 = "Abc"; String str3 = "abc"; System.out.println("Comparison between str1 and str2 = "+str1.equals(str2)); // false System.out.println("Comparison between str1 and str3 = "+str1.equals(str3)); //true } }

    Output:

    equals method output
    • compareTo(String anotherString): Compares two strings lexicographically (dictionary order), considering case. It returns:
      • 0 if the strings are equal.
      • A negative value if the first string is lexicographically less.
      • A positive value if the first string is lexicographically greater.
    public class StringInJava { public static void main(String[] args) { String str1 = "abc"; String str2 = "abcd"; String str3 = "abc"; String str4 = "ab"; System.out.println("Comparison between str1 and str2 = "+str1.compareTo(str2)); System.out.println("Comparison between str1 and str3 = "+str1.compareTo(str3)); System.out.println("Comparison between str3 and str4 = "+str3.compareTo(str4)); } }

    Output:

    compareTo method output

    compareToIgnoreCase(String anotherString): Similar as compareTo() and without case sensitive.

    public class StringInJava { public static void main(String[] args) { String str1 = "abc"; String str2 = "Abcd"; String str3 = "Abc"; String str4 = "ab"; System.out.println("Comparison between str1 and str2 = "+str1.compareToIgnoreCase(str2)); System.out.println("Comparison between str1 and str3 = "+str1.compareToIgnoreCase(str3)); System.out.println("Comparison between str3 and str4 = "+str3.compareToIgnoreCase(str4)); } }

    Output:

    compareToIgnoreCase method output

    StringBuilder: (Oracle_Docs_Jdk8_For_Inbuilt_Methods_Of_StringBuilder)#

    This class provides an API compatible with StringBuffer, but with no guarantee of synchronization. A mutable sequence of characters. Instances of StringBuilder are not safe for use by multiple threads. If such synchronization is required then it is recommended that StringBuffer be used. Every string builder has a capacity. As long as the length of the character sequence contained in the string builder does not exceed the capacity, it is not necessary to allocate a new internal buffer. If the internal buffer overflows, it is automatically made larger.

    public class StringInJava { public static void main(String[] args) { StringBuilder sb = new StringBuilder("Hello"); sb.append(" World"); // StringBuilder allows appending without creating new objects System.out.println(sb.toString()); // "Hello World" } }

    Output:

    StringBuilder output

    StringBuffer: (Oracle_Docs_Jdk8_For_Inbuilt_Methods_Of_StringBuffer)#

    String buffers are safe for use by multiple threads. A string buffer is like a String, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls. Every string buffer has a capacity. As long as the length of the character sequence contained in the string buffer does not exceed the capacity, it is not necessary to allocate a new internal buffer array. If the internal buffer overflows, it is automatically made larger.

    public class StringInJava { public static void main(String[] args) { StringBuffer sb = new StringBuffer("Hello"); sb.append(" World"); // StringBuffer allows thread-safe appending System.out.println(sb.toString()); // "Hello World" } }

    Output:

    StringBuffer output

    Conclusion:#

    This article highlights the differences between String, StringBuffer, and StringBuilder in Java. String is immutable and efficient in memory usage, while StringBuffer is thread-safe but slower due to synchronization. StringBuilder offers better performance in single-threaded environments as it is mutable and not synchronized.

    Java
    String
    String Pool
    StringBuilder
    StringBuffer

    More articles