Hi,
Welcome to JavaRanch!
Consider this (illegal) code in which "x" is not final:
This method starts a
thread which sleeps for a while, then prints a local variable's value. After it starts the thread, it loops for a while, incrementing the variable, then returns.
There are two cases to consider. Let's say that the Thread wakes up and prints the variable x while the "while" loop is still running. Then the thread prints some number between 1 and 100000. Everything's fine.
But what if it wakes up
after the while loop has completed? Then "foo()" will return. When the thread wakes up, the local variable "x" has gone out of scope. What should happen? Obviously, some kind of an error.
But
Java is defined to make this impossible. Local classes don't have any kind of direct reference to a local variable -- they make a copy of the variable when they are created. This avoids the going-out-of-scope problem. For this to appear consistent, the variable has to be final; otherwise, the copy and the original could end up with different values, and that would be very confusing!