Java is an object-oriented programming language where variables play a crucial role in storing and managing data. Among them, static and non-static (instance) variables are very important concepts every beginner must understand.
What is a Variable in Java?
A variable is a container used to store data values. In Java, variables are mainly categorized based on how they are declared and used.
Two important types are:
- Static variables
- Non-static (instance) variables
Static Variables in Java
A static variable is a variable that is shared among all objects of a class. It belongs to the class rather than any specific object.
Key Features
- Declared using the static keyword
- Only one copy exists for the entire class
- Shared across all objects
- Memory is allocated once when the class is loaded
Example
class Student {
static String college = "ABC College";
}
public class Main {
public static void main(String[] args) {
System.out.println(Student.college);
}
}
Output
ABC College
Non-Static (Instance) Variables
A non-static variable (also called an instance variable) belongs to an object. Each object has its own copy.
Key Features
- No static keyword used
- Each object has its own value
- Stored in heap memory
- Created when an object is created
Example
class Student {
String name;
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student();
s1.name = "Harini";
System.out.println(s1.name);
}
}
Output
Harini
Top comments (0)