Example & Tutorial understanding programming in easy ways.

14.what is the use of final keyword with Variables?

In Java the final keyword can be used with the variables also. If a Java variable is declared as final and initialized by some value using an initializer or an assignment statement can not be initialized again. Initialization of variable is not required at the time of declaration. Such type of final variables are called "blank final" variable. These blank final instance variable/s must be assigned inside the constructor of the class in which they are declared. Likewise, the blank final static variable must be assigned inside the static initializer of the class in which they are declared.

Syntax for declaring a variable as final:-

public class AreaOfCircle {

public static final double PI = 3.14;

public final double radius = 8;

[...]

}

 

Syntax for declaring a variable as blank final:

public class AreaOfCircle {

public static final double PI = 3.14;

public final double radius;

AreaOfCircle(double r) {

radius = r;

}

[...]

}

 

Read More →