Non-Static Variables
- In Java, variables are used to store data. Based on how memory is allocated and how values are shared, variables can be static or non-static (instance).
- Understanding this difference is important for writing efficient and well-structured programs.
Non-Static (Instance) Variables
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 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
A static variable is declared using the static keyword. It belongs to the class, not to individual objects. Only one copy of a static variable exists, shared by all objects of the class.
Key Points
- Created once when the class is loaded
- Shared among all objects
- Stored in method area
- Accessed using 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;
}
}
Top comments (0)