Search code examples
javaoopfinal

Understanding of final variable


Suppose a class contains a final variable. Why is new space allocated for final variable every time an object of the class is created even though its value can't be changed? Why its memory allocation is not like a static variable?


Solution

  • Consider this example:

    public class Example {
        public final int someNum;
        // constructor
        public Example(int n) {
            someNum = n;
        }
    }
    

    Here in this example, every object of this class might have a different value for someNum, even though it is a final variable. Therefore new space must be allotted for every instance of the class.