Java static variable

Java Programming Java8Object Oriented Programming

The static keyword is used to create variables that will exist independently of any instances created for the class. Only one copy of the static variable exists regardless of the number of instances of the class.

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


The static modifier is used to create class methods and variables, as in the following example −

Live Demo

public class InstanceCounter {

   private static int numInstances = 0;

   protected static int getCount() {
      return numInstances;

   private static void addInstance() {

   InstanceCounter() {

   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");


Started with 0 instances
Created 500 instances
Published on 23-Apr-2018 07:11:30