Lab 03: Strings & StringBuilder

🎯 Objective

Master Java's String class methods and use StringBuilder for efficient string manipulation.

📚 Background

In Java, String is immutable — every modification creates a new object. For repeated concatenation (e.g., in loops), use StringBuilder which mutates in place and is far more efficient. Java also offers String.format() and text blocks (Java 15+) for advanced formatting.

⏱️ Estimated Time

30 minutes

📋 Prerequisites

  • Completed Lab 1–2

🛠️ Tools Used

  • Docker (innozverse-java:latest)

🔬 Lab Instructions

Step 1: Basic String methods

📸 Verified Output:

Step 2: String comparison — never use ==

📸 Verified Output:

💡 Always use .equals() for String comparison. == checks if two variables point to the same object in memory.

Step 3: String splitting and joining

📸 Verified Output:

Step 4: String.format() and printf

📸 Verified Output:

💡 %-10s = left-aligned, 10-char wide. %3d = right-aligned, 3-wide integer. %.2f = 2 decimal places.

Step 5: StringBuilder — efficient concatenation

📸 Verified Output:

Step 6: Text blocks (Java 15+)

📸 Verified Output:

💡 Text blocks (triple-quoted strings) preserve indentation relative to the closing """. Great for JSON, SQL, HTML templates.

Step 7: String methods — chars and conversion

📸 Verified Output:

Step 8: Immutability performance benchmark

📸 Verified Output:

💡 StringBuilder outperforms String concatenation in loops by orders of magnitude because it doesn't create intermediate objects.

✅ Verification

📸 Verified Output:

🚨 Common Mistakes

  • Using == for String comparison: Always use .equals()

  • String in loop: Avoid s += x in loops — use StringBuilder

  • Off-by-one in substring: substring(0, 5) includes index 0–4 (5 is exclusive)

  • Null String: Calling methods on null throws NullPointerException

📝 Summary

String is immutable and rich with useful methods. For building strings dynamically, StringBuilder is the efficient choice. Use String.format() for structured output and text blocks for multi-line content.

🔗 Further Reading

Last updated