Purpose of final access modifier knows everyone, that is if any variable is declared as final, value of that variable can not be changed during run time. Normally all the constant variables will be declared in a constant class and that class will be referred throughout the project. In this case, if any constant value need to be changed which was declared as final, we have to compile all the class files which all are referring that constant class. Because final variables will be referred at the time of compilation only. During run time, final variables will not be referred. We will see below example,
Constant java file:We will compile both java files and execute the JavaPrint class file. Output will be 100
Now , we are modifying JavaConstant java file as belowNow, we are compiling JavaConstant java file alone and execute JavaPrint class file. Output will be 100 again. Because modified value of MIN_VAL will not be referred during run time since it is declared as final
Now, we will compile JavaPrint java file and execute JavaPrint class file. Output will be 150
No comments:
Post a Comment