Skip to main content
Advertisement

9.2 String & StringBuilder

One of the most heavily manipulated data types in Java programming is text, namely the String. Embedded tightly into the java.lang package, the String class offers an overwhelming arsenal of highly useful features.

In this chapter, we explore the core mechanism of StringImmutability—and two companion classes designed to circumvent its performance drawbacks: StringBuilder and StringBuffer.

1. The True Nature of String and 'Immutability'

In Java, String is not a primitive data type like int or char. It is a full-fledged class (object) containing an array of characters. Because it is an object, it has built-in methods.

However, the defining characteristic of a String instance is that once it is created in memory, its text contents can never, ever be modified (Immutability).

String a = "Hello";
a = a + " World"; // Does it crack open 'Hello' and cram ' World' at the end?
System.out.println(a); // Hello World

To a developer, it appears as though the box labeled a was cleverly updated to contain "Hello World". But under the hood in memory, the story is entirely different.

  1. Initially, a text instance "Hello" is spawned somewhere in memory.
  2. When + " World" runs, Java does not fetch the original "Hello" and append letters to it. Instead, it finds a completely empty spot in memory and mints a brand new"Hello World" string instance entirely from scratch!
  3. Finally, it repoints the a reference variable toward this newborn "Hello World". The old "Hello" is left orphaned, floating as space junk until the Garbage Collector sweeps it away.

Imagine joining together a million pieces of text in a loop using String (concat). A million brand-new individual string instances would be generated and immediately abandoned, causing a catastrophic memory and speed bottleneck!

2. Top 5 Most Useful String Methods

String is packed with dozens of handy utilities. Let's look at the ones you'll use constantly in the real world:

  1. length(): Returns the number of characters in the string. ("Java".length() -> 4)
  2. charAt(int index): Returns the specific character at the given index. ("Java".charAt(0) -> 'J')
  3. substring(int start, int end): Slices out a portion of the string between the given indices. ("Hello World".substring(0, 5) -> "Hello")
  4. replace(old, new): Replaces all matching old characters/strings with new ones.
  5. split(String regex): Chops the string into pieces based on a given delimiter string, returning a String[] array. ("apple,banana,orange".split(",") -> ["apple", "banana", "orange"])

3. The Savior of String Flaws: StringBuilder

We discussed the performance nightmare of repeatedly updating an "immutable" String. The ultimate solution is to use a Mutable (changeable) string class, namely StringBuilder(or StringBuffer).

StringBuilder is explicitly designed with a spacious internal buffer of memory. When you combine, insert, or delete text, it does not continuously spawn dumb new instances. Instead, it forcefully shoves or deletes text directly within its own existing buffer space. The speed and memory efficiency are absolutely unparalleled.

public class StringBuilderExample {
public static void main(String[] args) {
// Create an initial internal buffer containing "Start!"
StringBuilder sb = new StringBuilder("Start!");

// 1. append() : The absolute fastest way to slap text onto the end!
sb.append(" Java");
sb.append(" Programming");

// 2. insert() : Injects text exactly at a specific index.
sb.insert(6, " Fun");

// 3. delete() : Completely erases text within a specific boundary.
sb.delete(0, 6);

// Finally, convert the finished buffer back into a standard, read-only String.
String result = sb.toString();

System.out.println(result);
}
}

[Execution Result]

Fun Java Programming

Summary: When to Use What?

  • String: Use it for static, constant text that will rarely change, or for short bursts of text processing. (It is extremely safe and thread-secure due to its immutability).
  • StringBuilder: ** Mandatory**when you are programmatically assembling text inside loops, dynamically constructing SQL queries, or manipulating large text bodies extensively.

(Side note: StringBuffer is the thread-safe version of StringBuilder. StringBuilder ditches thread safety synchronization to achieve even faster speeds, making it the preferred choice for regular single-threaded operations.)

Advertisement