Java Static Keyword (static variable, static method, static block)
Java static Keyword: static Variable, static Method, static Block (With Examples)
✨ Quick Summary
In this post, you’ll learn what the static keyword means in Java. We will cover static variables, static methods, and static blocks with simple beginner-friendly examples.
In our previous post, we learned about Access Modifiers. Now, let’s learn one of the most important Java keywords: static.
1) What is static in Java?
The static keyword means the member belongs to the class, not the object.
That means:
- ✅ static variables are shared by all objects
- ✅ static methods can be called without creating an object
- ✅ static block runs automatically when class loads
2) static Variable in Java
A static variable is shared among all objects of the class.
⭐ Example: If you have 100 students, the college name is same for all. So college name can be static.
class Student {
String name;
static String college = "ABC College";
Student(String n) {
name = n;
}
void display() {
System.out.println(name + " - " + college);
}
}
public class StaticVariableExample {
public static void main(String[] args) {
Student s1 = new Student("Rahul");
Student s2 = new Student("Aishwarya");
s1.display();
s2.display();
}
}
3) static Method in Java
A static method can be called directly using the class name. You do not need to create an object.
class Demo {
static void show() {
System.out.println("Static method called!");
}
}
public class StaticMethodExample {
public static void main(String[] args) {
Demo.show(); // no object needed
}
}
4) static Block in Java
A static block runs automatically when the class loads. It runs before the main method.
public class StaticBlockExample {
static {
System.out.println("Static block executed!");
}
public static void main(String[] args) {
System.out.println("Main method executed!");
}
}
5) Important Notes (Interview Points)
- ✅ static members belong to class
- ✅ static is memory efficient
- ⚠️ static method cannot directly access non-static variables
- ⚠️ static method cannot use this keyword
Conclusion
The static keyword is used when you want to define the members that belong to the class. The static keyword is often used in actual Java programs and is also part of the interview questions.
- Next Post: Java this Keyword (this variable, this method, this constructor)

That was first-class work.
ReplyDelete