Master Core Java Concepts!
Subscribe to Ram N Java for clear explanations, practical code examples, and essential Java tutorials!
Subscribe Now on YouTubeTypes of Variables in Java
A variable is a container that holds data during the execution of a Java program. In Java, variables are categorized into three main types based on where and how they are defined:
- Instance Variables: Declared inside a class but outside of any method, constructor, or block, without the
statickeyword. Each created object gets its own copy. - Static Variables: Declared inside a class with the
statickeyword. Only one copy exists for the entire class, shared across all instances. - Local Variables: Declared inside a method, constructor, or block. They are accessible only within that specific scope.
Code Example: Defining Java Variables
class Student {
// Instance variable
String name;
// Static variable
static String schoolCode = "SCH101";
public void eat() {
// Local variable
int numberOfBiscuits = 10;
System.out.println("Number of biscuits eaten: " + numberOfBiscuits);
}
}
// Instance variable
String name;
// Static variable
static String schoolCode = "SCH101";
public void eat() {
// Local variable
int numberOfBiscuits = 10;
System.out.println("Number of biscuits eaten: " + numberOfBiscuits);
}
}
Accessing Different Variables in Java
public class StudentDemo {
public static void main(String[] args) {
// 1. Accessing instance variable via object reference
Student student = new Student();
student.name = "John";
System.out.println("Name: " + student.name);
// 2. Accessing static variable directly via class name
System.out.println("School Code: " + Student.schoolCode);
// 3. Calling method containing local variable
student.eat();
}
}
public static void main(String[] args) {
// 1. Accessing instance variable via object reference
Student student = new Student();
student.name = "John";
System.out.println("Name: " + student.name);
// 2. Accessing static variable directly via class name
System.out.println("School Code: " + Student.schoolCode);
// 3. Calling method containing local variable
student.eat();
}
}
Key Takeaways
✔️ Instance Variables: Tied to class objects; created when an object is instantiated.
✔️ Static Variables: Loaded when the class is loaded; best accessed using ClassName.variableName.
✔️ Local Variables: Temporary variables destroyed as soon as method execution finishes.