Java ProgramsOOPInstance Variables

Instance Variables in Java

beginner·  OOP  ·  Classes & Objects

Problem

An instance variable is a field declared inside a class but outside any method — each object created from that class gets its own separate copy, so changing one object's copy never affects another object's.

Create two Student objects and change one's age to show the other's age is unaffected.

Input
student1.age = 20, student2.age = 22
Output
Aditi's age: 20 Rohan's age: 22

Java Program

Java
class Student { String name; int age; } public class InstanceVariables { public static void main(String[] args) { Student student1 = new Student(); student1.name = "Aditi"; student1.age = 20; Student student2 = new Student(); student2.name = "Rohan"; student2.age = 22; // does not affect student1's age System.out.println(student1.name + "'s age: " + student1.age); System.out.println(student2.name + "'s age: " + student2.age); } }

Output

Aditi's age: 20 Rohan's age: 22

Core Logic

Creating two separate objects from the same class and assigning different values to their identically-named field shows each object keeps its own copy, not a shared one.

How It Works
  1. 1Student student1 = new Student(); and Student student2 = new Student(); create two entirely separate objects.
  2. 2student1.age = 20; sets a value on the first object only — it has no effect on student2.
  3. 3student2.age = 22; likewise only touches the second object's own copy of age.
  4. 4Printing both objects' age fields shows two different values, even though both came from the exact same class.
After setting student1.age = 20 and student2.age = 22, printing both shows 20 and 22 — each object remembers only what was assigned to it.
💡

Key Point: If age were declared static instead, both objects would share the exact same value — the fact that they don't here is what makes age an instance variable.

Key Concepts

instance variableobject statefield independence

Related Programs