English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

static keyword in Java programming

Static Modifier

Static Variables

InStaticThe keyword is used to create class variables that exist independently of all instances created by the class. There is only one copy of the static variable, regardless of the number of instances of the class.

Static variables are also known as class variables. Local variables cannot be declared as static.

Static Methods

The static keyword is used to create methods that exist independently of any instance created for the class.

Static methods do not use any instance variables of any objects defined by the class. Static methods get all the data from the parameters and calculate something from these parameters without referencing variables.

Class variables and methods can be accessed using the class name followed by a dot and the variable or method name.

Example

The static modifier is used to create class methods and variables, as shown in the following examples:

public class InstanceCounter {
   private static int numInstances = 0;
   protected static int getCount() {
      return numInstances;
   }
   private static void addInstance() {
      numInstances++;
   }
   InstanceCounter() {
      InstanceCounter.addInstance();
   }
   public static void main(String[] arguments) {
      System.out.println("Starting with ", + InstanceCounter.getCount() + " instances");
      for (int i = 0; i < 500; ++i) {
         new InstanceCounter();
      }
      System.out.println("Created ", + InstanceCounter.getCount() + " instances");
   }
}

Output Result

Starting with 0 instances
Created 500 instances