What Are Java Variables?
A variable is a container that stores data (like numbers, text, or true/false). Every variable has:
- A datatype
- A name
- A value
Types of Java Variables
1️⃣ Local Variables → Declared within a method, constructor, or block. → Accessible only within that block.
Example:
public class LocalVariableExample {
public static void main(String[] args) {
int number = 10; // Local variable
System.out.println(number);
}
}
2️⃣ Instance Variables → Declared within a class but outside methods. → Each instance (object) of the class gets its own copy.
Example:
public class InstanceVariableExample {
// Instance variable
int number = 20;
public static void main(String[] args) {
InstanceVariableExample object = new InstanceVariableExample();
System.out.println(object.number);
}
}
3️⃣ Static (Class) Variables
→ Declared with static
.
→ One copy for all instances of the class.
→ Accessible with the class name.
Example:
public class StaticVariableExample {
// Static variable
static int number = 30;
public static void main(String[] args) {
System.out.println(StaticVariableExample.number);
}
}
Summary
- Local variable — Inside methods or blocks, temporary.
- Instance variable — Inside class, for each object.
- Static (class) variable — Inside class, shared by all instances.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.