Class/static variables belong to a class, just like instance variables they are declared within a class, outside any method, but, with the static keyword.
They are available to access at the compile time, you can access them before/without instantiating the class, there is only one copy of the static field available throughout the class i.e. the value of the static field will be same in all objects. You can define a static field using the static keyword.
If you declare a static variable in a class, if you haven’t initialized it, just like with instance variables compiler initializes these with default values in the default constructor.
Yes, you can also initialize these values using the constructor.
Example
public class DefaultExample { static String name; static int age; DefaultExample() { name = "Krishna"; age = 25; } public static void main(String args[]) { new DefaultExample(); System.out.println(DefaultExample.name); System.out.println(DefaultExample.age); } }
Output
Krishna 25
Declaring final and static
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.
Example
public class DefaultExample { static final String name; static final int age; public static void main(String args[]) { new DefaultExample(); System.out.println(DefaultExample.name); System.out.println(DefaultExample.age); } }
Compile time error
DefaultExample.java:2: error: variable name not initialized in the default constructor static final String name; ^ DefaultExample.java:3: error: variable age not initialized in the default constructor static final int age; ^ 2 errors
But, if you try to initialize a variable which is declared final and static, compiler considers it as an attempt to initialize the variable and a compile time error will be generated.
Example
public class DefaultExample { static final String name; static final int age; DefaultExample() { name = "Krishna"; age = 25; } public static void main(String args[]) { new DefaultExample(); System.out.println(DefaultExample.name); System.out.println(DefaultExample.age); } }
Compile time error
OutputDeviceAssignedDefaultExample.java:5: error: cannot assign a value to final variable name name = "Krishna"; ^ DefaultExample.java:6: error: cannot assign a value to final variable age age = 25; ^ 2 errors