SrcForge

Lesson 17

Strings and StringBuffer

Strings are immutable character sequences in Java. StringBuffer and StringBuilder are mutable alternatives used for efficient string modification.

Java Track

Save progress as you learn.

61 lessons

Lesson content

Strings in Java represent sequences of characters. StringBuffer and StringBuilder create and modify mutable strings efficiently.

What are Strings in Java?

A String is a sequence of characters stored as an object of the String class. String objects are immutable — their values cannot be changed after creation.

Definition List

  • String: A class in Java used to represent a sequence of characters. String objects are immutable.
  • Immutable: An object whose value cannot be changed after it is created.
  • StringBuffer: A mutable and thread-safe class used for modifying strings.
  • StringBuilder: A mutable and non-thread-safe class used for faster string manipulation.
  • Substring: A portion of a string extracted from another string.
  • Thread-Safe: Ensures multiple threads cannot modify the same object simultaneously in an unsafe manner.

Why Strings are Immutable

Once a String object is created, its value cannot be modified. If changes are made, Java creates a new String object instead. This provides improved security, better memory management and thread safety.

Common String Methods in Java

  • length() — Returns the length of the string
  • charAt() — Returns a character at a specified index
  • equals() — Compares string contents
  • equalsIgnoreCase() — Compares strings ignoring case
  • toUpperCase() — Converts string to uppercase
  • toLowerCase() — Converts string to lowercase
  • replace() — Replaces characters or words
  • contains() — Checks whether a string contains a value
  • isEmpty() — Checks if a string is empty
  • startsWith() — Checks starting characters
  • endsWith() — Checks ending characters
  • substring() — Extracts part of a string
  • trim() — Removes leading and trailing spaces

Example 01: String Methods in Java

package String;

public class stringsConcept {
    public static void main(String args[]) {
        String a = "Programming in Java";
        String b = "Java is simple";

        System.out.println("A : " + a);
        System.out.println("B : " + b);

        System.out.println("A HashCode " + a.hashCode());
        System.out.println("B HashCode " + b.hashCode());
        System.out.println("Equals : " + a.equals(b));
        System.out.println("Equals Ignore Case: " + a.equalsIgnoreCase(b));
        System.out.println("Length: " + a.length());
        System.out.println("CharAt: " + a.charAt(0));
        System.out.println("Uppercase: " + a.toUpperCase());
        System.out.println("Lowercase: " + a.toLowerCase());
        System.out.println("Replace: " + a.replace("Programming in Java", " Oracle - Java"));
        System.out.println("Contains : " + a.contains("Java"));
        System.out.println("Empty : " + a.isEmpty());
        System.out.println("EndWith : " + a.endsWith("va"));
        System.out.println("StartWith : " + a.startsWith("Pro"));
        System.out.println("Substring : " + a.substring(5));
        System.out.println("Substring : " + a.substring(0, 5));

        char[] carray = a.toCharArray();
        for (char c : carray) {
            System.out.print(c + "   ");
        }

        String c = " Mentor  ";
        System.out.println("Length: " + c.length());
        System.out.println("C:" + c);
        System.out.println("C Trim :" + c.trim());
        System.out.println("C Trim Length:" + c.trim().length());
    }
}

Substring in Java

A substring is a part of an existing string.

public String substring(int startIndex)
public String substring(int startIndex, int endIndex)

StringBuffer and StringBuilder in Java

StringBuffer and StringBuilder are used when string content needs to be modified frequently. Unlike String objects, they are mutable.

Example 02: StringBuffer and StringBuilder

package String;

public class stringBuffer_stringBuilder {
    public static void main(String args[]) {
        StringBuilder buffer = new StringBuilder("Kishore");
        System.out.println(buffer);

        buffer.append(" ragav");
        System.out.println(buffer);

        buffer.insert(10, " Computer");
        System.out.println(buffer);

        buffer.replace(9, 11, "@@@");
        System.out.println(buffer);

        buffer.delete(9, 11);
        System.out.println(buffer);

        buffer.reverse();
        System.out.println(buffer);

        System.out.println(buffer.charAt(2));
        System.out.println(buffer.length());
        System.out.println(buffer.substring(0));
        System.out.println(buffer.substring(0, 5));

        buffer.setCharAt(0, '@');
        System.out.println(buffer);

        StringBuffer sb = new StringBuffer();
        System.out.println(sb.capacity()); // default 16

        sb.append("Hello");
        System.out.println(sb.capacity()); // still 16

        sb.append("java is my favourite language");
        System.out.println(sb.capacity()); // (16*2)+2 = 34
    }
}

Common StringBuffer Methods

  • append() — Adds text at the end
  • insert() — Inserts text at a specified position
  • replace() — Replaces characters
  • delete() — Removes characters
  • reverse() — Reverses the string
  • charAt() — Returns character at index
  • length() — Returns string length
  • substring() — Extracts part of the string
  • setCharAt() — Updates a character

StringBuffer in Java

StringBuffer is mutable, thread-safe and suitable for multithreaded applications.

StringBuilder in Java

StringBuilder is similar to StringBuffer but not synchronized. It is faster and best suited for single-threaded applications.

When to Use Each

  • Use String when content does not change frequently.
  • Use StringBuffer when multiple threads access the same string.
  • Use StringBuilder when modifications are frequent and thread safety is not required.

FAQ

1. What is the difference between String and StringBuffer?

String objects are immutable. StringBuffer objects are mutable and can be modified without creating new objects.

2. Which is faster: StringBuffer or StringBuilder?

StringBuilder is faster because it is not synchronized.

3. Why are Strings immutable in Java?

Strings are immutable to improve security, memory efficiency and thread safety.

String objects are immutable in Java.
StringBuffer is mutable and thread-safe.
StringBuilder is mutable but not thread-safe.
StringBuilder is faster than StringBuffer.
Use String for constant values, StringBuilder for frequent changes.
substring() extracts a portion of any string.
trim() removes leading and trailing whitespace.

Where Java is used

Java in real-world development

String Class

Immutable sequence of characters. Any modification creates a new object in memory.

StringBuffer

Mutable and thread-safe. Best for multithreaded environments where strings are modified frequently.

StringBuilder

Mutable and faster than StringBuffer. Best for single-threaded applications with frequent string changes.

String Methods

Built-in methods like length(), charAt(), contains(), replace() and trim() simplify string operations.

Substring

Use substring(start) or substring(start, end) to extract portions of a string.

Immutability Benefits

Immutable strings improve security, enable memory optimization through string pooling and ensure thread safety.

Prev: ArraysBack to hub