Clean β’ Professional
In Java, the static keyword is one of the most powerful and commonly used features. It is mainly used for memory management and for creating class-level members that are shared among all objects.
When a member (variable, method, or block) is declared static, it belongs to the class rather than any specific object.
That means:
Example:
class Student {
int rollNo; // Instance variable
static String college = "ABC University"; // Static variable
Student(int r) {
rollNo = r;
}
void display() {
System.out.println(rollNo + " - " + college);
}
}
public class StaticVariableExample {
public static void main(String[] args) {
Student s1 = new Student(101);
Student s2 = new Student(102);
s1.display();
s2.display();
}
}
Output:
101 - ABC University
102 - ABC University
Note : Both objects share the same college variable. If one object changes it, the change reflects in all objects.
Example:
class MathUtils {
static int square(int x) {
return x * x;
}
}
public class StaticMethodExample {
public static void main(String[] args) {
int result = MathUtils.square(5); // No object needed
System.out.println("Square: " + result);
}
}
Output:
Square: 25
Math.max(), Arrays.sort()).Example:
class Database {
static String connection;
static {
System.out.println("Static Block Executed");
connection = "Database Connected";
}
static void showStatus() {
System.out.println(connection);
}
}
public class StaticBlockExample {
public static void main(String[] args) {
Database.showStatus();
}
}
Output:
Static Block Executed
Database Connected
Note : Static blocks are useful for initializing static resources, configurations, or constants before program execution.
In Java, you can also create static nested classes inside another class.
Example:
class Outer {
static class Inner {
void display() {
System.out.println("Inside static nested class");
}
}
}
public class StaticNestedClassExample {
public static void main(String[] args) {
Outer.Inner obj = new Outer.Inner();
obj.display();
}
}
Output:
Inside static nested class
Note : A static nested class can access only static members of the outer class.
| Concept | Description |
|---|---|
| Static variable | Shared among all objects of a class |
| Static method | Belongs to the class, not object |
| Static block | Runs once when the class is loaded |
| Static nested class | Can access only static members of outer class |
| Access | Accessed using ClassName.memberName |
class Counter {
static int count = 0;
Counter() {
count++;
System.out.println("Object " + count + " created");
}
}
public class StaticExample {
public static void main(String[] args) {
new Counter();
new Counter();
new Counter();
}
}
Output:
Object 1 created
Object 2 created
Object 3 created
Note : Static variable count is shared β used to track how many objects are created.
Math, Collections, etc.)