Marking the local variable z as final fixes the problem :
Can anyone please explain what is happening ?
You have a method local class which is allowed to access final local variable in the scope it is created.
Does making a local-variable final allows it to stay alive even if the method gets completed and local variable goes out of scope?
final means it cannot be changed. Nothing else.
Does final local variables get stored on a heap instead of stack ?
All variables are allocated on the stack, final or not.
I know exactly why it can not compile in case I am trying to access a non-final local variable.
Perhaps you should think about this because its not clear to me that this is the case at all.
A nested class can "access" final variable as these are copied as fields of the object automatically. It does not support non-final fields as they could be changed, either by the method or the class and this is not supported because in reality there are two different fields/variables.