Static and Non-Static Variables in Java
Source: Dev.to
Non-Static (Instance) Variables
In Java, a non‑static variable is declared inside a class but outside any method, without using the static keyword. Each object of the class gets its own separate copy of the variable.
Key Points
- Created when an object is created
- Each object has a different value
- Stored in heap memory
- Accessed using an object reference
Example
class Student {
int marks;
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student();
Student s2 = new Student();
s1.marks = 80;
s2.marks = 90;
System.out.println(s1.marks); // 80
System.out.println(s2.marks); // 90
}
}
Here, marks is a non‑static variable, so each Student object has its own value.
Static Variables
Static variables belong to the class rather than any individual object.
Key Points
- Created once when the class is loaded
- Shared among all objects
- Stored in the method area
- Accessed using the class name (recommended)
Example
public class Employee {
String name;
int salary;
static String company_name = "TCS";
public static void main(String[] args) {
Employee mukesh = new Employee();
mukesh.name = "Mukesh kumar";
mukesh.salary = 10000;
Employee hari = new Employee();
hari.name = "Hari krishnan";
hari.salary = 20000;
}
}