Course contentsShow
← Java
Lesson 2172 of 2,87043. String Handling in DepthFree lesson

Defensive Copying Is Unnecessary

Understand that passing Strings between methods or classes is safe because they cannot be mutated.

Defensive Copying Is Unnecessary

What you'll learn: Why you don't need to create defensive copies when passing String objects between methods or classes.


In many object-oriented programs, defensive copying is a technique where you create a copy of a mutable object before passing it to another method or returning it from a method. This protects your internal state from unexpected changes. For example, if you pass an array or a mutable Date object, the receiver could modify it and corrupt your object's state.

Why Strings Are Different

Because String objects are immutable, defensive copying serves no purpose. Once a String is created, its contents cannot be changed—ever. Any operation that appears to modify a String actually creates a new String object.

This means you can safely:

  • Pass String parameters to methods without fear they'll be altered
  • Return String fields directly from getters
  • Store String references received from external code

The Analogy

Think of a String like a printed photograph sealed in plastic. You can look at it, you can pass it to someone else, but neither of you can alter what's in the picture. Compare this to a whiteboard (a mutable object)—if you hand someone a whiteboard, they might erase or change what's written on it.

In Practice

public class User {
    private String username;
    
    public User(String username) {
        // No need to copy: this.username = new String(username);
        this.username = username;  // Safe!
    }
    
    public String getUsername() {
        // No need to copy: return new String(username);
        return username;  // Safe!
    }
}

The caller cannot modify your internal username field through the reference you returned.

Key Takeaway:
Because Strings are immutable, you never need defensive copying—pass and return them freely without creating unnecessary object copies.