Java - Static variables

Java

In this tutorial we will learn about static variables of a class in Java programming language.

When we want to have a class member variable that can be used independently of any object of the class then we create a static variable.

Note! When instances i.e. objects of a class are created then they all share the same static variable. This is because the static variable is not copied for every object of the class.

Syntax of static variables

static dataType variableName;

Where, dataType is some valid data type and variableName is the name of the static variable.

Accessing the static variable

To access the static variable we have to use the following syntax.

ClassName.variableName

Where, ClassName is the name of a class and variableName is the name of the static variable of the class.

Example

In the following example we have the HelloWorld class and it has a static integer variable objectCount. The value of this static variable is incremented whenever a new object of the class is created.

class HelloWorld {

  // static variable
  static int objectCount = 0;

  // variable
  private int number;

  // constructor
  HelloWorld(int number) {
    this.number = number;

    // updating the static variable
    HelloWorld.objectCount++;
  }

  // method
  public int getNumber() {
    return this.number;
  }
}

public class Example {
  public static void main(String[] args) {

    System.out.println("Total number of objects of the Hello World class: " + HelloWorld.objectCount);

    // create an object
    System.out.println("Creating object obj.");
    HelloWorld obj = new HelloWorld(10);

    System.out.println("Total number of objects of the Hello World class: " + HelloWorld.objectCount);

    System.out.println("Hello World obj number: " + obj.getNumber());

    // create another object
    System.out.println("Creating object obj2.");
    HelloWorld obj2 = new HelloWorld(20);

    System.out.println("Total number of objects of the Hello World class: " + HelloWorld.objectCount);

    System.out.println("Hello World obj2 number: " + obj2.getNumber());

  }
}

Output:

$ javac Example.java 
$ java Example
Total number of objects of the Hello World class: 0
Creating object obj.
Total number of objects of the Hello World class: 1
Hello World obj number: 10
Creating object obj2.
Total number of objects of the Hello World class: 2
Hello World obj2 number: 2

So, in the above code we are creating two objects and each time we instantiate an object of the HelloWorld class we are incrementing the value of the static variable objectCount by 1 using the ++ increment operator.