Static variables − Static variables are also known as class variables. You can declare a variable static using the keyword. Once you declare a variable static there would only be one copy of it in the class, regardless of how many objects are created from it.
public static int num = 39;
final − Once you declare a variable final you cannot reassign value to it. When you declare a variable of a class static and final we are making it constant.
But if you declare an instance variable static and final Java compiler will not initialize it in the default constructor therefore, it is mandatory to initialize static and final variables. If you don’t a compile time error is generated.
class Data{ static final int num; } public class ConstantsExample { public static void main(String args[]) { System.out.println("value of the constant: "+Data.num); } }
ConstantsExample.java:2: error: variable num not initialized in the default constructor static final int num; ^ 1 error
class Data{ static final int num; Data(int i){ num = i; } } public class ConstantsExample { public static void main(String args[]) { System.out.println("value of the constant: "+Data.num); } }
ConstantsExample.java:4: error: cannot assign a value to final variable num num = i; ^ 1 error
To make this program work you need to initialize the final static variable in a static block as −
class Data{ static final int num; static{ num = 1000; } } public class ConstantsExample { public static void main(String args[]) { System.out.println("value of the constant: "+Data.num); } }
value of the constant: 1000