Static Keyword in Java

Introduction

In Java, the static keyword is a non-access modifier that can be applied to variables, methods, blocks, and nested classes. When a member is declared static, it belongs to the class rather than instances of the class. This means that static members are shared among all instances of the class and can be accessed without creating an instance of the class.

Uses of Static in Java

  1. Static Variables
  2. Static Methods
  3. Static Blocks
  4. Static Nested Classes

Static Variables

Definition: Static variables (also called class variables) are shared among all instances of a class. They are initialized only once at the start of the program execution.

Characteristics:

Example:

class Counter {
    static int count = 0;

    Counter() {
        count++;
        System.out.println(count);
    }

    public static void main(String[] args) {
        Counter c1 = new Counter();
        Counter c2 = new Counter();
        Counter c3 = new Counter();
    }
}

Static Methods

Definition: Static methods can be called without creating an instance of the class. They can access static variables and other static methods directly.

Characteristics: