Strings & Manipulation

☕ Java Lesson 4 Intermediate

Unlike primitives, strings in Java are reference objects of the String class. Java handles Strings in a highly optimized way via the String Pool.

1 String Immutability and the String Pool

Strings in Java are immutable; once created, their characters cannot be modified. Any manipulation method (like `toUpperCase()`) returns a brand new String object rather than editing the existing one.

To save memory, JVM houses a String Constant Pool. When you initialize a String using literal syntax (e.g. `String s1 = "Hello"`), the JVM checks the pool. If "Hello" exists, `s1` references it. If you initialize using `new String("Hello")`, Java creates a completely separate object in the heap. Therefore:

  • `s1 == s2` compares memory addresses (reference equality).
  • `s1.equals(s2)` compares literal character values (structural equality).
2 Common String Methods & StringBuilder

Let's run a program demonstrating core String methods and compare String concatenation with `StringBuilder` performance:

Java — String Manipulation ▶ Run Code
public class Main {
    public static void main(String[] args) {
        String greeting = "  Hello, Java Learners!  ";
        
        // Basic methods
        System.out.println("Length: " + greeting.length());
        System.out.println("Trimmed: '" + greeting.trim() + "'");
        System.out.println("Substring(9, 13): " + greeting.trim().substring(7, 11));
        
        // Equality comparison
        String str1 = "Java";
        String str2 = new String("Java");
        System.out.println("Comparing addresses (==): " + (str1 == str2));
        System.out.println("Comparing content (.equals): " + str1.equals(str2));

        // StringBuilder for modifications
        StringBuilder builder = new StringBuilder("Beginning");
        builder.append(" and Middle");
        builder.insert(0, "The ");
        System.out.println("StringBuilder Result: " + builder.toString());
    }
}
3 Code Challenge
Challenge: Create two string variables: one literal `"Programming"` and one using the `new String("Programming")` constructor. Write statements checking their equality with `==` and `.equals()`. Print out the results. Then use a `StringBuilder` to reverse the string and print the reversed value.