In java
, normally you'd think if a variable is defined as final
, its value will not change.
For example, the content of Main.java
:
|
|
The above code should always print 10
, right? Well, that's not the case. At least in this case:
|
|
This will print:
10
11
Reason for this?
Deserialization is implemented by the JVM on a level below the basic language constructs.1
So, language rules do not apply to JVM. The object was initialized with i = 10
and it was updated while deserialization despite being final
.
Code sample on GitHub: https://github.com/njkevlani/final-in-java-code.