+ 2
Can we intialize blank final variable?
Can we intialize blank final variable?
2 Answers
+ 1
If I understand you correctly, then yes.
A statement like
private final String myString;
has not been given a value yet, so its first assignment will be its only assignment. Often you see the assignment when the variable is declared. A final variable must refer to the same object throughout the course of the object's life. Any attempt to assign a new object (either with new String() or as the return of a method call) will result in an error
0
There are two options for assigning the value for final instance variable:
a) direct when declaring the variable like
class MyClass {
private final String myString = "This is a constant";
}
b) or you MUST assign it in the constructor like
class MyClass {
private final String myString;
public MyClass() {
myString = "This is a constant";
}
// it is also possible to pass the value for the final
// string as parameter into the constructor
public MyClass(String aString) {
myString = aString;
}
}