Harikrishna Gorrepati wrote:Let me change the code..With this, there is no error. I am getting the error in 2 cases when final variable is NOT initialized with any value
1. declared constructor
2. try to get value from final variable (It is not taking default value i.e., 0)
The final variable should be initialized in the same line, which were declared. Otherwise, you should initialize that variable in every Constructors or one of the instance initializer. Because, the final variable can be initialized only once. If it takes the default value, and because of the final, the value can't be changed in the future. So, this is non-sense. That's why, they don't get initialized with default value as like other non final instance variables.
|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|
Similarly, every blank final variable must be assigned at most once; it must be definitely unassigned when an assignment to it occurs. Such an assignment is defined to occur if and only if either the simple name of the variable, or its simple name qualified by this, occurs on the left hand side of an assignment operator. A Java compiler must carry out a specific conservative flow analysis to make sure that, for every assignment to a blank final variable, the variable is definitely unassigned before the assignment; otherwise a compile-time error must occur.
SCJP 6 [86%] June 30th, 2010
OCPWCD [84%] March 26th, 2012
OCEJPAD [83%] September 6th, 2014
If you find any post useful, click the "plus one" sign on the right