How does this Java code snippet work? (String pool and reflection) [duplicate]

Solution 1:

What happened to Mario ??

You changed it, basically. Yes, with reflection you can violate the immutability of strings... and due to string interning, that means any use of "Mario" (other than in a larger string constant expression, which would have been resolved at compile-time) will end up as "Luigi" in the rest of the program.

This kinds of thing is why reflection requires security permissions...

Note that the expression str + " " + "Mario" does not perform any compile-time concatenation, due to the left-associativity of +. It's effectively (str + " ") + "Mario", which is why you still see Luigi Luigi. If you change the code to:

System.out.println(str + (" " + "Mario"));

... then you'll see Luigi Mario as the compiler will have interned " Mario" to a different string to "Mario".

Solution 2:

It was set to Luigi. Strings in Java are immutable; thus, the compiler can interpret all mentions of "Mario" as references to the same String constant pool item (roughly, "memory location"). You used reflection to change that item; so all "Mario" in your code are now as if you wrote "Luigi".

Solution 3:

To explain the existing answers a bit more, let's take a look at your generated byte code (Only the main() method here).

Byte Code

Now, any changes to the content's of that location will affect both the references (And any other you give too).