Member-only story
Can You Change the Value of a final String
Using Reflection? | Tricky Java Interview Questions — Part 15
Hello Developers,
Welcome to Part 15 of the Tricky Java Interview Questions series.
Here’s today’s head-scratcher:
Can you change the value of a
final String
in Java using reflection?
Let’s answer it directly, then explore how and why — with a live example.
Quick Answer
✅ Yes, you can change the value of a
final String
using reflection — but you really shouldn’t.
Why? Because doing so breaks Java’s safety model, and results in undefined, fragile, and JVM-dependent behavior.
Still, let’s explore how it’s possible — and what the risks are.
Using Reflection to Modify a final
String
Reflection allows inspection and modification of classes, methods, and fields at runtime. By leveraging reflection, it’s possible to access and modify private fields, including the internal character array of a String
.
Example:
import java.lang.reflect.Field;
public class FinalStringReflection {
public static void main(String[] args) throws Exception {
final String original = new String("immutable"); // Not interned
System.out.println("Before: " + original);
Field valueField =…