Java Programming/Keywords/static

From Wikibooks, open books for an open world
Jump to: navigation, search

static is a Java keyword. It can be applied to a field, a method or an inner class. A static field, method or class has a single instance for the whole class that defines it, even if there is no instance of this class in the program. For instance, a Java entry point (main()) has to be static. A static method cannot be abstract. It must be placed before the variable type or the method return type. It is recommended to place it after the access modifier and before the final keyword:

Example Code section 1: Static field and method.
1 public static final double PI = 3.1415926535;
3 public static void main(final String[] arguments) {
4    //…
5 }

The static items can be called on an instantiated object or directly on the class:

Example Code section 2: Static item calls.
1 double aNumber = MyClass.PI;
2 MyClass.main(new String[0]);

Static methods cannot call nonstatic methods. The this current object reference is also not available in static methods.


  • Static variables can be used as data sharing amongst objects of the same class. For example to implement a counter that stores the number of objects created at a given time can be defined as so:
Computer code Code listing 1:
 1 public CountedObject {
 2    private static int counter;
 4    public AClass() {
 6       counter++;
 7    }
 9    public int getNumberOfObjectsCreated() {
10       return counter;
11    }
12 }

The counter variable is incremented each time an object is created.

Public static variable should not be used, as these become global variables that can be accessed from everywhere in the program. Global constants can be used, however. See below:

Example Code section 3: Constant definition.
1 public static final String CONSTANT_VAR = "Const";
  • Static methods can be used for utility functions or for functions that do not belong to any particular object. For example:
Computer code Code listing 2:
1 public ArithmeticToolbox {
3    public static int addTwoNumbers(final int firstNumber, final int secondNumber) {
4         return firstNumber + secondNumber;
5    }
6 }
See also Static methods