What is a Variable in Java?
A variable is used to store data in a program.
Each variable has:
- A type (int, String, etc.)
- A name
- A value
Example:
int age = 10;
Types of Variables in Java
Java variables can be mainly classified into
- Global variables
- Local variables
- Static variables
- Non-static (Instance) variables
Let’s understand these using the below example.
Example Code
public class School {
// Global variable / Instance variable / Non-static variable
String name;
int std;
// Global and non-static variable
int age = 10;
// Global variable and static variable
static String school_name = "ABC.scl";
public static void main(String[] args) {
School tamil_teacher1 = new School(); // Object or Instance
tamil_teacher1.name = "Mukesh";
System.out.println(tamil_teacher1.name);
School tamil_teacher2 = new School();
tamil_teacher2.name = "Karthick";
System.out.println(tamil_teacher2.name);
School English_teacher = new School(); // Object or Instance
English_teacher.name = "Guru";
System.out.println(English_teacher.name);
System.out.println(School.school_name);
test();
}
public static void test() {
School math_teacher = new School();
math_teacher.name = "Yogesh";
System.out.println(math_teacher.name);
// Local variable
int age = 10;
System.out.println(age);
}
}
1. Global Variables
Variables declared inside a class but outside methods are called global variables.
Example:
String name;
int age;
These variables:
- Belong to the class
- Can be accessed using an object
2. Non-Static (Instance) Variables
Non-static variables are also called instance variables because:
- Each object gets its own copy
- Values can be different for each object
Example:
School tamil_teacher1 = new School();
tamil_teacher1.name = "Mukesh";
School tamil_teacher2 = new School();
tamil_teacher2.name = "Karthick";
Here, both objects have different name values.
3. Static Variables
A static variable belongs to the class, not to objects.
Example:
static String school_name = "ABC.scl";
Features:
- Only one copy exists
- Shared by all objects
- Accessed using the class name
Example:
System.out.println(School.school_name);
4. Local Variables
A local variable is declared inside a method.
Example:
int age = 10;
Local variables:
- Exist only inside the method
- Cannot be accessed outside the method
- Must be initialized before use
Important note:
- Static methods cannot directly access non-static variables
- Non-static variables need an object to be accessed
That’s why we create objects inside methods to access name.
Top comments (0)