VOOZH about

URL: https://www.geeksforgeeks.org/java/static-keyword-java/

⇱ static Keyword in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

static Keyword in Java

Last Updated : 10 Nov, 2025

The static keyword in Java is used for memory management and belongs to the class rather than any specific instance. It allows members (variables, methods, blocks, and nested classes) to be shared among all objects of a class.

  • Memory is allocated only once when the class is loaded.
  • No object creation is needed to access static members; use the class name directly.
  • Static methods and variables can’t access non-static members directly.
  • Static methods can’t be overridden because they belong to the class, not instances.

Types of Static Members in Java

The static keyword can be applied to four main components:

1. Static Variables

A static variable is also known as a class variable. It is shared among all instances of the class and is used to store data that should be common for all objects.


Output
101 Ravi GFG
102 Amit GFG

2. Static Blocks

A static block is executed only once when the class is first loaded into memory. It is often used to initialize static variables or perform configuration tasks before the main method executes.


Output
Static block initialized.
from main
Value of a : 10
Value of b : 40

3. Static Methods

A static method belongs to the class rather than to any object. It can be called directly using the class name.

  • Can access only static data directly.
  • Cannot access instance variables or methods directly.
  • Cannot use this or super keywords.

Output
From m1
Inside static block
Value of a: 20
From main

4. Static Nested Classes 

A static nested class is a class declared as static inside another class. It can be accessed without creating an object of the outer class.


Output
Static Nested Class Method

Note: The Inner class is accessed using the outer class name (Outer.Inner).

Static vs Non-Static

The table below demonstrates the difference between Static and Non-Static

AspectStaticNon-Static
Belongs ToClass (shared by all objects)Individual object (unique per instance)
Memory AllocationCreated once when class is loadedCreated separately for each object
Access MethodAccessed using class nameAccessed using object reference
Can AccessOnly other static members directlyBoth static and non-static members
Common UseUtility methods, constants, shared dataObject-specific data and behavior
Comment
Article Tags: