Lesson 8 • Intermediate

    Java Strings

    Strings are the most commonly used type in real-world Java. Every user input, every file name, every database query, every error message — they're all strings. In this lesson, you'll learn to search, compare, split, format, and efficiently build strings. You'll also learn the #1 Java gotcha: why == doesn't work for comparing strings.

    What You'll Learn

    • ✅ Creating strings and concatenation
    • ✅ Immutability — why strings can never be changed
    • ✅ The String Pool — how Java saves memory with string reuse
    • ✅ Essential methods: length, charAt, substring, indexOf, contains
    • ✅ Comparing strings with .equals() vs == (critical!)
    • ✅ Transforming: toUpperCase, replace, trim, split, join
    • ✅ StringBuilder — efficient string building in loops
    • ✅ String.format() — clean formatted output

    💡 Real-World Analogy

    A String is like a necklace of letter beads. Each bead is a character, and you can examine them, count them, or create a new necklace — but you can never change the beads on an existing necklace. Every "change" actually creates a brand new necklace. This is called immutability.

    1️⃣ Creating Strings & Concatenation

    You create strings by wrapping text in double quotes. You can combine strings using the + operator (concatenation):

    // Creating strings
    String name = "Alice";
    String greeting = "Hello, World!";
    
    // Concatenation — joining strings together
    String message = "Hello, " + name + "!";
    // → "Hello, Alice!"
    
    // Concatenating different types (auto-converted to String)
    int age = 25;
    String info = name + " is " + age + " years old";
    // → "Alice is 25 years old"
    
    // ⚠️ Watch out for order of operations!
    System.out.println("Score: " + 5 + 3);   // "Score: 53" (strings!)
    System.out.println("Score: " + (5 + 3));  // "Score: 8"  (math first)

    2️⃣ Immutability & The String Pool

    Immutability means once a String is created, it can never be changed. Every method that seems to "modify" a string actually creates a brand new string and returns it. The original is untouched.

    String name = "Alice";
    name.toUpperCase();         // Creates "ALICE" but we don't store it!
    System.out.println(name);   // Still "Alice" — original unchanged!
    
    name = name.toUpperCase();  // ✅ Now name points to "ALICE"
    System.out.println(name);   // "ALICE"

    Java also maintains a String Pool — a special memory area that reuses identical string literals:

    String a = "Hello";              // Goes to String Pool
    String b = "Hello";              // Reuses same object!
    String c = new String("Hello");  // Forces NEW object (bypasses pool)
    
    a == b     // true  (same pool object)
    a == c     // false (different objects!)
    a.equals(c) // true  (same content ✓)

    🔑 This is why == is unreliable for strings! It compares memory addresses, not content. Two strings can have identical text but be different objects in memory. Always use .equals().

    3️⃣ Essential String Methods

    These are the methods you'll use every day. Memorize these and you'll handle 90% of string tasks:

    String text = "Hello, World!";
    
    // === INSPECTING ===
    text.length()              // 13 (number of characters)
    text.charAt(0)             // 'H' (first character)
    text.charAt(6)             // 'W' 
    text.isEmpty()             // false
    text.isBlank()             // false (Java 11+, checks whitespace too)
    
    // === SEARCHING ===
    text.contains("World")     // true
    text.indexOf("World")      // 7 (position where "World" starts)
    text.indexOf("xyz")        // -1 (not found)
    text.lastIndexOf("l")      // 10 (last occurrence)
    text.startsWith("Hello")   // true
    text.endsWith("!")          // true
    
    // === TRANSFORMING (returns NEW string!) ===
    text.toUpperCase()         // "HELLO, WORLD!"
    text.toLowerCase()         // "hello, world!"
    text.substring(0, 5)       // "Hello" (from index 0 to 4)
    text.substring(7)          // "World!" (from index 7 to end)
    text.replace("World", "Java") // "Hello, Java!"
    "  spaces  ".trim()        // "spaces"
    
    // === SPLITTING & JOINING ===
    "a,b,c".split(",")        // String[] {"a", "b", "c"}
    String.join(" - ", "a", "b", "c")  // "a - b - c"

    Try It: String Methods

    Explore searching, transforming, and splitting strings

    Try it Yourself »
    JavaScript
    // 💡 Try modifying this code and see what happens!
    // String Methods — Java logic simulated in JavaScript
    console.log("=== String Methods ===\n");
    
    let text = "Hello, World!";
    console.log("Text: '" + text + "'\n");
    
    // 1️⃣ Inspecting
    console.log("1. INSPECTING:");
    console.log("   length: " + text.length);
    console.log("   charAt(0): '" + text.charAt(0) + "'");
    console.log("   charAt(7): '" + text.charAt(7) + "'");
    
    // 2️⃣ Searching
    console.log("\n2. SEARCHING:");
    console.log("   contains 'World'
    ...

    4️⃣ String Comparison — The #1 Java Gotcha

    This is the single most common bug Java beginners make. Let's be absolutely clear about it:

    // ❌ WRONG — compares memory addresses, not content!
    String input = scanner.nextLine();  // user types "yes"
    if (input == "yes") { ... }  // MIGHT work, might not! Unreliable!
    
    // ✅ CORRECT — compares actual text content
    if (input.equals("yes")) { ... }
    
    // ✅ Case-insensitive comparison
    if (input.equalsIgnoreCase("YES")) { ... }
    
    // ✅ Null-safe trick — put the constant first
    if ("yes".equals(input)) { ... }  // Won't crash even if input is null!
    
    // ❌ CRASH if input is null
    if (input.equals("yes")) { ... }  // NullPointerException!

    🔑 The rule: == checks "are these the exact same object in memory?" .equals() checks "do these contain the same text?" You almost always want .equals().

    5️⃣ StringBuilder — Efficient String Building

    Because strings are immutable, concatenation in a loop creates a new string object every iteration. For large loops, this wastes massive amounts of memory. Use StringBuilder instead:

    // ❌ SLOW — creates 1000 temporary String objects!
    String result = "";
    for (int i = 0; i < 1000; i++) {
        result += i + ", ";  // New String EVERY time
    }
    
    // ✅ FAST — uses one mutable buffer
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < 1000; i++) {
        sb.append(i).append(", ");
    }
    String result = sb.toString();
    
    // StringBuilder methods:
    sb.append("text");      // Add to end
    sb.insert(0, "start");  // Insert at position
    sb.delete(0, 5);        // Remove characters
    sb.reverse();            // Reverse the content
    sb.length();             // Current length
    sb.toString();           // Convert to String

    💡 Rule of thumb: If you're concatenating in a loop, use StringBuilder. For a few simple concatenations outside loops, regular + is fine.

    6️⃣ String.format() — Clean Formatted Output

    Instead of ugly concatenation with lots of + signs, use String.format() for readable, clean string construction:

    String name = "Alice";
    int age = 30;
    double gpa = 3.857;
    
    // ❌ Hard to read with concatenation
    String msg1 = "Name: " + name + ", Age: " + age + ", GPA: " + gpa;
    
    // ✅ Clean with String.format()
    String msg2 = String.format("Name: %s, Age: %d, GPA: %.1f", name, age, gpa);
    // → "Name: Alice, Age: 30, GPA: 3.9"
    
    // Format specifiers:
    // %s  = String
    // %d  = integer
    // %f  = floating-point
    // %.2f = 2 decimal places
    // %n  = newline
    // %10s = right-padded to 10 chars
    // %-10s = left-padded to 10 chars

    Try It: StringBuilder & Formatting

    Build strings efficiently and format output cleanly

    Try it Yourself »
    JavaScript
    // 💡 Try modifying this code and see what happens!
    // StringBuilder & Formatting — Java logic simulated in JavaScript
    console.log("=== StringBuilder & Formatting ===\n");
    
    // 1️⃣ StringBuilder simulation
    console.log("1. STRING BUILDING IN A LOOP:");
    let parts = [];
    for (let i = 1; i <= 10; i++) {
      parts.push("Item" + i);
    }
    console.log("   " + parts.join(", "));
    console.log("   (In Java: use StringBuilder.append() for this!)");
    
    // 2️⃣ String.format simulation
    console.log("\n2. FORMATTED OUTPUT
    ...

    7️⃣ Real-World String Patterns

    Here are patterns you'll use constantly in real Java applications:

    // Email validation (basic)
    boolean validEmail = email.contains("@") && email.contains(".");
    
    // File extension check
    if (filename.endsWith(".java")) { ... }
    if (filename.endsWith(".pdf") || filename.endsWith(".doc")) { ... }
    
    // Parsing CSV data
    String line = "Alice,25,3.85";
    String[] parts = line.split(",");
    String name = parts[0];        // "Alice"
    int age = Integer.parseInt(parts[1]);  // 25
    double gpa = Double.parseDouble(parts[2]); // 3.85
    
    // Creating URL slugs
    String slug = title.toLowerCase()
        .replaceAll("[^a-z0-9]+", "-")  // Replace non-alphanumeric
        .replaceAll("^-|-$", "");        // Remove leading/trailing dashes
    
    // Sanitizing user input
    String clean = input.trim()             // Remove leading/trailing spaces
        .replaceAll("\\s+", " ");        // Collapse multiple spaces

    Try It: Real-World String Problems

    Palindrome checker, word counter, email validator, and CSV parser

    Try it Yourself »
    JavaScript
    // 💡 Try modifying this code and see what happens!
    // Real-World String Problems — Java logic simulated in JavaScript
    console.log("=== Real-World String Problems ===\n");
    
    // 1️⃣ Palindrome checker
    function isPalindrome(str) {
      let clean = str.toLowerCase().replace(/[^a-z0-9]/g, "");
      return clean === clean.split("").reverse().join("");
    }
    console.log("1. PALINDROME CHECKER:");
    let words = ["racecar", "hello", "A man a plan a canal Panama", "level", "world"];
    for (let w of words) {
      console.l
    ...

    Common Mistakes

    • ❌ Using == instead of .equals():
      if (name == "Alice")       // ❌ Compares memory addresses
      if (name.equals("Alice"))  // ✅ Compares text content
    • ❌ Forgetting strings are immutable:
      name.toUpperCase();        // ❌ Result thrown away!
      name = name.toUpperCase(); // ✅ Store the new string
    • ❌ Calling methods on null: null.length() crashes with NullPointerException. Always check for null first, or use the constant-first pattern: "expected".equals(input).
    • ❌ Concatenation in loops: Creates thousands of temporary objects. Use StringBuilder instead.
    • ❌ Confusing length vs length(): Arrays: arr.length (property). Strings: str.length() (method with parentheses).

    Pro Tips

    💡 Use .equalsIgnoreCase() for user input — users might type "YES", "Yes", or "yes".

    💡 Use .strip() instead of .trim() (Java 11+) — it handles Unicode whitespace properly.

    💡 Use String.format() for readable string construction instead of chaining + operators.

    💡 Java 15+ text blocks: Use """multi-line text""" for SQL queries, HTML, and JSON.

    💡 String.join() is your friend: String.join(", ", list) is cleaner than manual loops.

    📋 Quick Reference

    MethodExampleResult
    length()"Hello".length()5
    charAt(i)"Hello".charAt(1)'e'
    equals()"Hi".equals("Hi")true
    substring(a,b)"Hello".substring(0,3)"Hel"
    indexOf()"Hello".indexOf("ll")2
    split()"a,b".split(",")["a","b"]
    replace()"Hi".replace("H","B")"Bi"
    trim()" Hi ".trim()"Hi"
    format()String.format("%s=%d","x",5)"x=5"

    🎉 Lesson Complete!

    You now know how to create, compare, search, split, format, and efficiently build strings in Java! Strings appear in virtually every Java program — from parsing user input to building SQL queries to formatting log messages.

    Next up: Object-Oriented Programming — learn to design classes and objects, the foundation of all Java applications.

    Sign up for free to track which lessons you've completed and get learning reminders.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy PolicyTerms of Service