Pages

Thursday, February 14, 2013

Constant and final keyword usage in Java


Constants are variables which once set cannot be changed i.e., once a value is set then it cannot be altered whatsoever. Local variables inside methods can also be declared as final. 


Fields of a class may be declared as public static final - that way they are available to other classes, but cannot be changed by those other classes. An example is Math.PI. Classes and methods may also be marked as final.Constants' values may be set in an explicit initialization, in a separate line of code, or, as method parameters passed when the method is called. Constants' values may be set in an explicit initialization, in a separate line of code within an initialization block, or even in a constructor.

Example Program : http://pastie.org/6159101

The above program also has the wrong usage and initialization of values to final variables.

0 comments:

Post a Comment