Error
The final field cannot be assigned
The final field cannot be assigned
Error Type
Compile Time
Compile Time
Sample Code
public class Test {
int element1;
final String element2 = "Hello";
private void method1(){
element2 = "World";
}
}
int element1;
final String element2 = "Hello";
private void method1(){
element2 = "World";
}
}
Cause
Final variables cannot be reassigned. Final variables are assigned while or before object construction only.
Resolution
Either we should make element as non-final
public class Test {
private int element1;
private String element2 = "Hello";
private void method1(){
element2 = "World";
}
}
private int element1;
private String element2 = "Hello";
private void method1(){
element2 = "World";
}
}
or
shouldn't try to reassign the final variable.
public class Test {
private int element1;
private String element2 = "Hello";
private void method1(){
// removed re-assignment code
}
}
private int element1;
private String element2 = "Hello";
private void method1(){
// removed re-assignment code
}
}