Understanding Static or Class Variable in Java

In this class, We discuss Understanding Static or Class variables in Java.

The reader should have prior knowledge of class and instance variables. Click here.

We take an example and understand static variables in Java.

Example:

The below diagram shows the example code.

The above code contains static variable p.

The memory is allocated to static variables during compile time.

Whenever the class loads to RAM, the static variables are assigned memory in the heap.

In the above example, we had an instance variable.

Whenever we create an object, memory is assigned, for instance, variables.

In our example, we created two objects, each with its own instance variables space.

A static variable is common to all the objects.

Any object can access and modify static variables.

The static variable is global to all the objects of the class.