What are class variables in Java?

The class variables must have the keyword static as the modifier and are declared inside a class body but outside of any method bodies.

Only one copy of class variables are created from the point the class is loaded into the JVM until the the class is unloaded, regardless of the number of object instances that are created from that class.

If one object instance of that class changes the value of a class variable then all the other instances see the same changed value.

You access a class variable directly through the class or through an object instance. Accessing a class variable through the class by specifying the name of the class, followed by a dot, followed by the name of the variable.

Class variables can be initialized by an assignment statement. Unassigned declaration of  class variables will get the default value as instance variables.

Class variables are not serialized. Static method can access static variables and can't access instance variables.

There are two excpetions:

Class variable has "static final" modifiers which must be assigned a value at the declaration time or inside the static initializer. You can only assign one time and can not reassign its value late.

Class variables can be declared with or without the keyword static within an interface declaration. Every field declaration in the body of an interface is implicitly public, static, and final. It is permitted to redundantly specify any or all of these modifiers for such fields.

Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend

Previous Next vertical dots separating previous/next from contents/index/pdf Contents

  |   |