Java String Handling and StringBuffer

Loading

In Java, String and StringBuffer are two fundamental classes used for handling text. They serve different purposes and have distinct characteristics. Let’s explore both in detail:


1. String Class

The String class represents an immutable sequence of characters. Once a String object is created, its value cannot be changed.

Key Features of String:

  • Immutable: Once created, the content of a String cannot be modified.
  • Stored in String Pool: Java maintains a special memory area called the String Pool to store String literals for reusability.
  • Thread-Safe: Since String is immutable, it is inherently thread-safe.

Common Methods of String:

  • length(): Returns the length of the string.
  • charAt(int index): Returns the character at the specified index.
  • substring(int beginIndex): Returns a substring from the specified index.
  • concat(String str): Concatenates the specified string to the end of the current string.
  • equals(Object obj): Compares the content of two strings.
  • toLowerCase() / toUpperCase(): Converts the string to lowercase or uppercase.
  • trim(): Removes leading and trailing whitespace.

Example:

public class StringExample {
    public static void main(String[] args) {
        String str1 = "Hello";
        String str2 = "World";

        // Concatenation
        String result = str1.concat(" ").concat(str2);
        System.out.println(result); // Output: Hello World

        // Length
        System.out.println("Length: " + result.length()); // Output: 11

        // Substring
        System.out.println("Substring: " + result.substring(6)); // Output: World

        // Comparison
        System.out.println("Equals: " + str1.equals("Hello")); // Output: true
    }
}

2. StringBuffer Class

The StringBuffer class represents a mutable sequence of characters. It is used when you need to modify the content of a string frequently.

Key Features of StringBuffer:

  • Mutable: The content of a StringBuffer can be modified.
  • Thread-Safe: All methods in StringBuffer are synchronized, making it thread-safe.
  • Better Performance for Modifications: Since StringBuffer is mutable, it avoids creating multiple objects during modifications, making it more efficient than String for frequent changes.

Common Methods of StringBuffer:

  • append(String str): Appends the specified string to the end.
  • insert(int offset, String str): Inserts the string at the specified position.
  • delete(int start, int end): Deletes the substring from start to end-1.
  • reverse(): Reverses the sequence of characters.
  • toString(): Converts the StringBuffer to a String.

Example:

public class StringBufferExample {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("Hello");

        // Append
        sb.append(" World");
        System.out.println(sb); // Output: Hello World

        // Insert
        sb.insert(5, " Java");
        System.out.println(sb); // Output: Hello Java World

        // Delete
        sb.delete(5, 10);
        System.out.println(sb); // Output: Hello World

        // Reverse
        sb.reverse();
        System.out.println(sb); // Output: dlroW olleH
    }
}

3. StringBuilder Class

The StringBuilder class is similar to StringBuffer but is not thread-safe. It is faster than StringBuffer because it does not have the overhead of synchronization.

Key Features of StringBuilder:

  • Mutable: Like StringBuffer, the content can be modified.
  • Not Thread-Safe: Methods are not synchronized.
  • Better Performance: Faster than StringBuffer for single-threaded applications.

Example:

public class StringBuilderExample {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("Hello");

        // Append
        sb.append(" World");
        System.out.println(sb); // Output: Hello World

        // Insert
        sb.insert(5, " Java");
        System.out.println(sb); // Output: Hello Java World

        // Delete
        sb.delete(5, 10);
        System.out.println(sb); // Output: Hello World

        // Reverse
        sb.reverse();
        System.out.println(sb); // Output: dlroW olleH
    }
}

4. Comparison Between String, StringBuffer, and StringBuilder

FeatureStringStringBufferStringBuilder
MutabilityImmutableMutableMutable
Thread-SafetyThread-safe (immutable)Thread-safe (synchronized)Not thread-safe
PerformanceSlow for modificationsFaster than StringFastest
Use CaseStoring fixed textFrequent modifications in multi-threaded environmentsFrequent modifications in single-threaded environments

5. When to Use Which?

  • Use String when:
  • The text is fixed and won’t change.
  • You need thread safety (due to immutability).
  • Use StringBuffer when:
  • You need to modify the text frequently in a multi-threaded environment.
  • Use StringBuilder when:
  • You need to modify the text frequently in a single-threaded environment.

6. Example Combining String, StringBuffer, and StringBuilder

public class StringHandlingExample {
    public static void main(String[] args) {
        // String
        String str = "Hello";
        str = str.concat(" World");
        System.out.println("String: " + str); // Output: Hello World

        // StringBuffer
        StringBuffer sbuffer = new StringBuffer("Hello");
        sbuffer.append(" World");
        System.out.println("StringBuffer: " + sbuffer); // Output: Hello World

        // StringBuilder
        StringBuilder sbuilder = new StringBuilder("Hello");
        sbuilder.append(" World");
        System.out.println("StringBuilder: " + sbuilder); // Output: Hello World
    }
}

By understanding the differences between String, StringBuffer, and StringBuilder, you can choose the right tool for your specific use case in Java!

Leave a Reply

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