String (The Stone Tablet): Imagine carving a sentence into stone. If you want to add a word at the end, you can’t just "insert" it. You have to get a whole new slab of stone and carve the entire new sentence from scratch.
StringBuilder (The Whiteboard): This is a special tool designed for efficiency. You can write, erase, and append text without needing to buy a new "board" every time. It’s much faster for heavy text manipulation.
Common String Methods
Java gives us a "Swiss Army Knife" of tools to inspect text:
.length(): How many characters?.toUpperCase()/.toLowerCase(): Change the casing..contains("abc"): Does it have these letters?.substring(start, end): Cut a piece out of the text.
The Code Example:
public class TextPro {
public static void main(String[] args) {
// --- 1. The Immutable String ---
String greeting = " Hello Java! ";
System.out.println("Original: [" + greeting + "]");
System.out.println("Trimmed: [" + greeting.trim() + "]"); // Removes spaces
System.out.println("Upper: " + greeting.toUpperCase());
System.out.println("Starts with 'H'? " + greeting.trim().startsWith("H"));
// --- 2. The Efficient StringBuilder ---
// Let's build a long string using a loop
StringBuilder sb = new StringBuilder();
sb.append("Alphabet: ");
for (char c = 'A'; c <= 'E'; c++) {
sb.append(c).append(" "); // Adding characters efficiently
}
// We can also modify the middle
sb.insert(0, "THE "); // Adds "THE " at the beginning
sb.reverse(); // Flip the whole thing!
System.out.println("\nStringBuilder Result:");
System.out.println(sb.toString());
}
}Expected Output:
Original: [ Hello Java! ]
Trimmed: [Hello Java!]
Upper: HELLO JAVA!
Starts with 'H'? true
StringBuilder Result:
E D C B A :tebahplA EHTn a real-world app—like a chat app or a search engine—you are processing millions of characters per second. If you use regular String concatenation (str = str + "new text") inside a loop, your app will lag. Using StringBuilder makes your code professional and high-performance.
Key Rule: Use
Stringfor simple labels or data that doesn't change. UseStringBuilderwhen you are building long pieces of text or modifying text inside loops.