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); } }
Krishna 25