Text Manipulation with String and StringBuilder in Java

Master text manipulation in Java using String and StringBuilder classes, including text blocks, string operations, and performance considerations for the OCP 21 exam.

Table of Contents

1. String Fundamentals

The String class in Java represents a sequence of characters. Strings are objects in Java, not primitives.

1.1 Creating Strings

There are multiple ways to create String objects:

Example:
// String literal (stored in string pool)
String str1 = "Hello";
String str2 = "Hello";  // Reuses same object from pool

// Using new keyword (creates new object)
String str3 = new String("Hello");
String str4 = new String("Hello");  // Different object

// From char array
char[] chars = {'H', 'e', 'l', 'l', 'o'};
String str5 = new String(chars);

// Empty string
String empty = "";
String empty2 = new String();

1.2 String Pool

Java maintains a string pool (intern pool) to optimize memory usage. String literals are automatically interned.

Example:
String s1 = "Java";
String s2 = "Java";
String s3 = new String("Java");

System.out.println(s1 == s2);        // true (same reference)
System.out.println(s1 == s3);      // false (different objects)
System.out.println(s1.equals(s3)); // true (same content)

// Manual interning
String s4 = s3.intern();
System.out.println(s1 == s4);      // true (now in pool)

2. String Immutability

Strings in Java are immutable - once created, they cannot be changed. Any operation that appears to modify a string actually creates a new string object.

Important: String immutability ensures thread safety and allows string pooling. However, frequent string modifications can be inefficient.
Example:
String str = "Hello";
str = str + " World";  // Creates NEW string object
// Original "Hello" object is unchanged (may be garbage collected)

// Multiple concatenations create multiple objects
String result = "";
for (int i = 0; i < 1000; i++) {
    result += i;  // Creates new string each iteration (inefficient!)
}
// Better to use StringBuilder for this

3. String Methods

The String class provides numerous methods for string manipulation.

3.1 Length and Character Access

Example:
String str = "Hello World";

int length = str.length();           // 11
char first = str.charAt(0);          // 'H'
char last = str.charAt(str.length() - 1);  // 'd'

// Get characters as array
char[] chars = str.toCharArray();

3.2 Substring Operations

Example:
String str = "Hello World";

// substring(startIndex) - from index to end
String sub1 = str.substring(6);      // "World"

// substring(startIndex, endIndex) - start inclusive, end exclusive
String sub2 = str.substring(0, 5);  // "Hello"
String sub3 = str.substring(6, 11);  // "World"

3.3 Searching and Replacing

Example:
String str = "Hello World";

// Searching
boolean contains = str.contains("World");     // true
int index = str.indexOf("World");             // 6
int lastIndex = str.lastIndexOf("l");         // 9
boolean starts = str.startsWith("Hello");      // true
boolean ends = str.endsWith("World");          // true

// Replacing
String replaced = str.replace("World", "Java");  // "Hello Java"
String replacedAll = str.replaceAll("l", "L");   // "HeLLo WorLd"
String replacedFirst = str.replaceFirst("l", "L"); // "HeLlo World"

3.4 Case Conversion

Example:
String str = "Hello World";

String upper = str.toUpperCase();    // "HELLO WORLD"
String lower = str.toLowerCase();    // "hello world"

3.5 Trimming and Whitespace

Example:
String str = "  Hello World  ";

String trimmed = str.trim();         // "Hello World" (removes leading/trailing whitespace)
boolean isEmpty = str.isEmpty();    // false
boolean isBlank = str.isBlank();    // false (Java 11+)

String blank = "   ";
boolean blankCheck = blank.isBlank();  // true (Java 11+)

3.6 Splitting and Joining

Example:
String str = "apple,banana,orange";

// Splitting
String[] fruits = str.split(",");    // ["apple", "banana", "orange"]
String[] parts = str.split(",", 2);  // ["apple", "banana,orange"] (limit)

// Joining (Java 8+)
String joined = String.join("-", "a", "b", "c");  // "a-b-c"
String joined2 = String.join(", ", fruits);       // "apple, banana, orange"

4. String Comparison

String comparison can be done using == (reference equality) or equals() (content equality).

4.1 Reference vs Content Equality

Example:
String s1 = "Java";
String s2 = "Java";
String s3 = new String("Java");

// Reference comparison (==)
System.out.println(s1 == s2);        // true (same object in pool)
System.out.println(s1 == s3);       // false (different objects)

// Content comparison (equals)
System.out.println(s1.equals(s2));   // true
System.out.println(s1.equals(s3));   // true

// Case-insensitive comparison
System.out.println("Java".equalsIgnoreCase("JAVA"));  // true

4.2 Lexicographic Comparison

Example:
String s1 = "apple";
String s2 = "banana";

int result = s1.compareTo(s2);      // negative (s1 < s2)
int result2 = s2.compareTo(s1);     // positive (s2 > s1)
int result3 = s1.compareTo(s1);     // 0 (equal)

// Case-insensitive comparison
int result4 = "Apple".compareToIgnoreCase("apple");  // 0
Remember: Always use equals() for content comparison, not ==. Use compareTo() for ordering.

5. Text Blocks (Java 15+)

Text blocks (introduced in Java 15, finalized in Java 15) allow multi-line string literals without escape sequences.

5.1 Text Block Syntax

Text blocks use triple quotes (""") and preserve formatting:

Example:
// Traditional multi-line string (verbose)
String html = "<html>\n" +
              "  <body>\n" +
              "    <p>Hello</p>\n" +
              "  </body>\n" +
              "</html>";

// Text block (clean)
String html2 = """
               <html>
                 <body>
                   <p>Hello</p>
                 </body>
               </html>
               """;

5.2 Text Block Features

  • Preserves line breaks and indentation
  • Automatically removes incidental whitespace
  • Supports escape sequences when needed
  • Can be used with string methods
Example:
// JSON example
String json = """
              {
                "name": "John",
                "age": 30
              }
              """;

// SQL query
String query = """
               SELECT * FROM users
               WHERE age > 18
               ORDER BY name
               """;

// With escape sequences
String text = """
              Line 1\nLine 2
              Line 3
              """;

6. StringBuilder Class

StringBuilder is a mutable sequence of characters, designed for efficient string concatenation and modification.

6.1 Creating StringBuilder

Example:
// Empty StringBuilder
StringBuilder sb1 = new StringBuilder();

// With initial capacity
StringBuilder sb2 = new StringBuilder(50);

// With initial string
StringBuilder sb3 = new StringBuilder("Hello");

// With CharSequence
StringBuilder sb4 = new StringBuilder((CharSequence) "World");

6.2 StringBuilder Methods

Example:
StringBuilder sb = new StringBuilder("Hello");

// Appending
sb.append(" World");           // "Hello World"
sb.append(123);               // "Hello World123"
sb.append(true);              // "Hello World123true"

// Inserting
sb.insert(5, ",");            // "Hello, World123true"

// Deleting
sb.delete(11, 14);            // "Hello, Worldtrue" (removes "123")
sb.deleteCharAt(5);          // "Hello Worldtrue" (removes comma)

// Replacing
sb.replace(6, 11, "Java");    // "Hello Javatrue"

// Reversing
sb.reverse();                 // "eurt avaJ olleH"

// Getting length and capacity
int len = sb.length();        // current length
int cap = sb.capacity();      // current capacity

// Converting to String
String result = sb.toString();

6.3 Method Chaining

StringBuilder methods return the StringBuilder instance, allowing method chaining:

Example:
StringBuilder sb = new StringBuilder()
    .append("Hello")
    .append(" ")
    .append("World")
    .append("!")
    .insert(5, ",");

String result = sb.toString();  // "Hello, World!"

7. StringBuffer Class

StringBuffer is similar to StringBuilder but is thread-safe (synchronized).

7.1 StringBuffer vs StringBuilder

Feature StringBuilder StringBuffer
Thread Safety Not thread-safe Thread-safe (synchronized)
Performance Faster Slower (due to synchronization)
When to Use Single-threaded environments Multi-threaded environments
Java Version Java 5+ Java 1.0+
Recommendation: Use StringBuilder unless you specifically need thread safety. In most cases, StringBuilder is preferred due to better performance.

8. Performance Considerations

8.1 String Concatenation Performance

Inefficient (creates many objects):
String result = "";
for (int i = 0; i < 1000; i++) {
    result += i;  // Creates new String object each iteration
}
Efficient (uses StringBuilder):
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
    sb.append(i);  // Modifies same object
}
String result = sb.toString();

8.2 When to Use Each

  • String: Use for immutable strings, string literals, and when you don't need to modify
  • StringBuilder: Use for frequent string modifications in single-threaded code
  • StringBuffer: Use for frequent string modifications in multi-threaded code

9. Exam Key Points

Critical Concepts for OCP 21 Exam:

  • String Immutability: Strings cannot be changed; operations create new objects
  • String Pool: String literals are interned and reused from the pool
  • == vs equals(): == compares references, equals() compares content
  • substring(): substring(start, end) - start inclusive, end exclusive
  • Text Blocks: Use """ for multi-line strings (Java 15+)
  • StringBuilder: Mutable, not thread-safe, use for frequent modifications
  • StringBuffer: Mutable, thread-safe, slower than StringBuilder
  • Performance: Avoid string concatenation in loops; use StringBuilder
  • Method Chaining: StringBuilder methods return the instance for chaining
  • compareTo(): Returns negative if less, positive if greater, 0 if equal
  • split(): Returns array, second parameter limits the number of splits
  • trim(): Removes leading and trailing whitespace only
  • isBlank() vs isEmpty(): isBlank() checks for whitespace (Java 11+)

Post a Comment

0 Comments