Can we intialize blank final variable? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Can we intialize blank final variable?

Can we intialize blank final variable?

25th Nov 2017, 8:25 PM
King David
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
25th Nov 2017, 10:59 PM
Dan Walker
Dan Walker - avatar
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; } }
26th Nov 2017, 6:48 PM
Weazel