Final static variable in JavaUtilizing an instance variable when its value is unchanged is not a good idea. We may then apply a static modification to that variable at that point. Whenever we declare the variable static, a single variable is generated at the class level and shared by all the objects. Any modification to that static variable will impact the activities of all other objects. If we don't initialize a static variable, JVM will automatically assign it a default value. But, while declaring the static variable with the final modifier, we must use the appropriate conventions:
Important points about the final static variable:1. Initialization of variable MandatoryWhen a static variable is declared as final, it needs to be manually initialized regardless of whether it is used since the JVM will not provide a default value for the final static variable. Filename: ExampleProgram.java Output: error: variable value not initialized in the default constructor 2. Initialization before class loading :Before class loading is complete, we must execute initialization on the final static variable. A final static variable can be initialized when it is declared. Filename: ExampleProgram2.java Output: 56 3. Initialize inside a static blockSince we must create a final static variable before the class and know that the static block is performed before the main() Method, we may also initialize a final static variable inside a static block. Filename: ExampleProgram.java Output: Value of MAX_VALUE: 100 We will obtain a compile-time error if we try to initialize a final static variable somewhere other than the abovementioned techniques. Filename: ExampleProgram.java Output: error: cannot assign a value to final variable value Implementation of final static variableLet's see an example where we can use the final static variable. Filename: Circle.java Output: Circle 1 - Radius: 5 Circle 1 - Area: 78.53975 Circle 1 - Circumference: 31.4159 Circle 2 - Radius: 10 Circle 2 - Area: 314.159 Circle 2 - Circumference: 62.8318 Next TopicJava File Watcher |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India