3.Would the Behavior Be Different with an Immutable Object?
2 min read
Short Answer
No, the fundamental behavior of Optional remains identical. Whether an object is mutable (like StringBuilder) or immutable (like String or Integer), an Optional always holds a reference to an object in memory. Reassigning the original local variable will still not affect what the Optional contains.
Example with an Immutable Object (String)
Let’s look at the exact same logic using a String, which is an immutable object in Java:
import java.util.Optional;public class App { public static void main(String[] args) { String text = "test"; Optional<String> textOp = Optional.of(text); text = null; // Reassigns the local variable 'text' if (textOp.isPresent()) { System.out.println("textOp is not null"); // Prints this } textOp.ifPresent(System.out::println); // Prints "test" }}
Output
textOp is not nulltest
Why Is It the Same?
Pass-by-Value References: In Java, variables hold references (pointers) to objects on the heap. When you write Optional.of(text), Java copies the reference value (the memory address) into the Optional container.
Variable Reassignment vs. Mutation: Doing text = null changes the local variable text to point to null. It does not change the memory address that was already copied and stored inside textOp.
When Does Immutability Matter for Optional?
While the Optional container itself behaves the same way, immutability changes how you interact with the contents inside the Optional:
Safety with Immutable Objects
Because immutable objects (like String, Integer, LocalDate) cannot be changed after creation, passing them around inside an Optional is entirely thread-safe. You never have to worry about another part of your code modifying the underlying state of the object while it lives inside the Optional.
If you put a mutable object inside an Optional, code outside the Optional can still modify that object’s internal state (e.g., calling sb.append("ed") on the original StringBuilder), which will reflect when you read it from the Optional because they both point to the exact same heap object. With immutable objects, even that risk is eliminated!