Java Tutorial

Constants in Java

Constant is an identifier whose value cannot be changed during execution of the program.

In JAVA to make the identifiers are as constants, we use a keyword called final.

Final is a keyword which is playing an important role in three levels. They are at variable level, at method level and at class level.

i. When we don?t want to change the value of the variable, then that variable must be declared as final.

Syntax for Final Variable Initialization:

Final data type v1=val1, v2=val2 ? vn=valn;

For example:

Final int	a=10;
                a=a+20; //invalid 
                a=30; //invalid

ii. When the final variable is initialized, no more modifications or assignments are possible.


Final data type v1, v2???vn;

For example:

Final int	a;
                a=a+1; //invalid a=30+2; //invalid
                a=400; //valid for 1st time
                a=500; //invalid

Whenever a final variable is declared first time assignment is possible and no more modification and further assignments are not possible. Hence, final variables cannot be modified.