⚡Static
The static keyword
The static
keyword in Java is used for memory management. It allows defining:
Static variables
Static methods
Static blocks
Static nested classes
A static member belongs to the class, not instances of the class.
A common use is static variables that hold global values shared across all objects. For example, a counter tracking total objects created.
Static methods also don't require making an object. They belong to the class and can be called using ClassName.method() style.
Static variables
A static variable is shared by all instances of a class. It's memory is allocated when the class is loaded.
Here, college
is static as it's the same for all students.
Static methods
A static method belongs to the class. It can be invoked without creating an instance.
⚡ Rules for Static in Java ⚡
The static
keyword in Java indicates something is related to the class itself, rather than individual instances of the class. There are some key rules around using static.
📊 Rules for Static Variables 📊
Declared using
static
keywordBelong to the class, rather than objects
A single copy exists that is shared across all objects
Accessible through the class name rather than objects
For example:
Only one copy of name
exists even if multiple App
objects are created.
⚙️ Rules for Static Methods ⚙️
Declared with
static
keywordCan be called without creating an object
Cannot access non-static members directly
For example:
sum()
is a utility method callable by MathUtils.sum(...)
without instantiating MathUtils
.
🧱 Rules for Static Blocks 🧱
Declared with
static { }
Executed when class is first loaded
Used to initialize static variables
For example:
This initializes the static name
when the class loads.
🏢 Rules for Static Nested Classes 🏢
Declared as
static
inside another classCan access only static members of outer class
No reference to instance of outer class
For example:
So those are some key rules to follow for proper usage of static in Java.
Main method
The main()
method must be static as JVM looks for a static method to start execution.
Last updated