Static vs Non-Static in Java
When learning Java, one very important concept is Static vs Non-Static (Instance).
If you understand this clearly, Java and OOP will become much easier.
What is Static?
static is a keyword used to create variables or methods that belong to the class, not to objects.
Example:
class Student {
static String college = "ABC College";
}
Access:
System.out.println(Student.college);
Key Idea:
- Only one copy is created
- Shared by all objects
- No need to create an object
What is Non-Static? (Instance)
Non-static means it belongs to an object (instance).
Example:
class Student {
int id;
String name;
}
Access:
Student s1 = new Student();
s1.id = 101;
s1.name = "Ram";
** Key Idea:**
- Each object has its own copy
- Must create an object to use it
✔️ rollNo, name → Non-static
✔️ college → Static
When to Use Static?
Use static when data is common for all objects:
- Shared values
- Utility methods
- Constants
When to Use Non-Static?
Use non-static when data is different for each object:
- Student name
- Employee salary
- Product details
Important Rule
A static method cannot directly access non-static variables
Wrong:
class Test {
int x = 10;
static void show() {
System.out.println(x); // Error
}
}
Correct:
class Test {
int x = 10;
static void show() {
Test obj = new Test();
System.out.println(obj.x);
}
}
Real-Life Example
College System
class Student {
int rollNo; // Unique for each student
String name; // Unique for each student
static String college = "ABC"; // Same for all students
}
rollNo, name → Non-static
college → Static
Top comments (0)