Java Programming/Keywords/static

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;
 3    ...
 4    public AClass {
 5       ...
 6       counter++;
 7    }
 8    ...
 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 {
2    ...
3    public static int addTwoNumbers(final int firstNumber, final int secondNumber) {
4         return firstNumber + secondNumber;
5    }
6 }
See also Static methods

  This article uses material from the Wikipedia page available here. It is released under the Creative Commons Attribution-Share-Alike License 3.0.



Connect with defaultLogic
What We've Done
Led Digital Marketing Efforts of Top 500 e-Retailers.
Worked with Top Brands at Leading Agencies.
Successfully Managed Over $50 million in Digital Ad Spend.
Developed Strategies and Processes that Enabled Brands to Grow During an Economic Downturn.
Taught Advanced Internet Marketing Strategies at the graduate level.

Manage research, learning and skills at Create an account using LinkedIn to manage and organize your omni-channel knowledge. is like a shopping cart for information -- helping you to save, discuss and share.

  Contact Us