static variable :
*A static Variable belongs to the class, not to an object.
- nly one copy is created and shared by all objects.
Example:
class Student {
static String college = "Bala";
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student();
Student s2 = new Student();
System.out.println(s1.college);
System.out.println(s2.college);
}
}
Output:
Bala
Bala
Non-Static Variable (Instance Variable):
A non-static variable belongs to an object.
Every object gets its own copy of the variable.
Example:
class Student {
String name;
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student();
Student s2 = new Student();
s1.name = "Bala";
s2.name = "Kumar";
System.out.println(s1.name);
System.out.println(s2.name);
}
}
Output:
Bala
Kumar
Explanation:
s1 → name = Bala
s2 → name = Kumar
Each object has a separate copy of name.
Key Differences:
| Static Variable | Non-Static Variable |
|---|---|
| Belongs to class | Belongs to object |
| One copy only | Separate copy for each object |
| Shared by all objects | Not shared |
| Access using class name | Access using object |
Top comments (0)