Strings

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 5 min

TL;DR

  • A String in Java is an Object that represents a sequence of characters.
  • Strings are immutable: Once a String object is created, its data/state cannot be changed. Any operation that alters a string (like .toUpperCase()) actually returns a brand new String object.
  • Strings are managed specially by the JVM using a String Pool to save memory.

Concept

Because strings are so commonly used in programming, Java treats them specially. Though String is a class (and a reference type), it can be instantiated using string literals without the new keyword.

Immutability

When you modify a String, Java creates a new String in memory and points the reference variable to the new one. The old String is left behind for garbage collection (unless it’s in the String Pool). This makes Strings inherently thread-safe.

Examples

public class StringExample {
    public static void main(String[] args) {
        // Creating a String
        String greeting = "Hello";
        
        // "Modifying" a string
        String loudGreeting = greeting.toUpperCase(); // Creates a NEW string "HELLO"
        
        System.out.println(greeting);      // Outputs: Hello (original is unchanged)
        System.out.println(loudGreeting);  // Outputs: HELLO
        
        // Common Methods
        int len = greeting.length();
        char firstLetter = greeting.charAt(0);
        boolean containsH = greeting.contains("H");
        
        // String concatenation
        String fullName = "John" + " " + "Doe";
    }
}

Interview Questions

Q: Why are Strings immutable in Java?
A: 1. Security: Strings are used for network connections, database URLs, and file paths. If they were mutable, a hacker could change a reference after security checks have passed.
2. Synchronization/Concurrency: Immutable objects are automatically thread-safe and can be shared among multiple threads without synchronization.
3. Caching / String Pool: The String Pool only works because Strings are immutable. If multiple references point to the same String literal, changing one would unexpectedly change the others if they were mutable.
4. Hashing: The hashcode of a String is cached at the time of creation. This makes Strings extremely fast to use as keys in a HashMap.