final keyword
final keyword can be used for variables, methods and class.1. final variable:
Once a value has been assigned to a final variable, it cannot be changed. These are constants. It's a good practice to write them in CAPS.Example 1:
class Test{ public static void main(String args[]){ Hello h = new Hello(); h.CONST = 30; } } class Hello{ final int CONST = 20; } /* Compile Time Error Test.java:4: error: cannot assign a value to final variable CONST h.CONST = 30; ^ 1 error */
Blank Final Variable
A blank final variable is a final variable which is not initialized while declaring the variable. It can be either be initialized in the Instance Initialization block (IIB) or Constructor. If it's not declared in any of these, then it will throw C.T.E.
Example 2 :
class Test{ public static void main(String args[]){ Hello h = new Hello(); } } class Hello{ final int CONST; //If a blank final variable is not initialized here, then // it has to be initialized either in IIB or Constructor. Hello(){ CONST = 30; } { //CONST=20; } } /* Compiles and executes fine. */
Blank static final variable
If a static variable is not initialized during declaration, then it can be initialized in a static block.
Example 3 :
class Test{ public static void main(String args[]){ Hello h = new Hello(); } } class Hello{ static final int CONST; //If blank static final variable is not initialized here, then // it has to be initialized in the static block. static{ CONST=8 } } /* Compiles and executes fine. */
No comments:
Post a Comment