Final in Java
Last updated on 2025-10-19 (history).
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:
| |
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.