← Back to Chapters

Java static Keyword

⚡ Java static Keyword

? Quick Overview

The static keyword in Java is used to define class-level members. Static members belong to the class itself rather than to individual objects.

? Key Concepts

  • Static members are shared across all objects
  • Static methods can be called without creating objects
  • Static variables store common data
  • Static blocks execute once during class loading

? Syntax / Theory

  • Static Variable: One copy shared by all instances
  • Static Method: Can access only static members
  • Static Block: Used for one-time initialization

? Code Example(s)

? View Code Example
// Example demonstrating static variable and method
class Counter {
static int count = 0;

static void increment() {
count++;
}

public static void main(String[] args) {
Counter.increment();
Counter.increment();
System.out.println(count);
}
}

?️ Live Output / Explanation

Output

2

The static variable count is shared across method calls. Each call to increment() updates the same variable.

? Interactive Demo: Static vs. Instance

Click the buttons below to see how memory works differently for Static vs Instance variables.

Class Level (Shared)

static int sharedCount = 0

Changes everywhere!

Object 1 (obj1)

int instanceCount = 0
static sharedCount = 0

Object 2 (obj2)

int instanceCount = 0
static sharedCount = 0

✅ Tips & Best Practices

  • Use static for utility methods and constants
  • Avoid static variables for object-specific data
  • Static methods cannot use instance variables directly

? Try It Yourself

  • Create a static block and print a message from it
  • Track the number of objects created using a static counter