Instance Variable in Java

instance-variable-in-java-feature.jpg

If you’ve been learning Java for a while, you already know that variables are an inevitable part of the language. Now, Java doesn’t just give you one type of variable to play with; rather, it gives you three:

  • Local variables
  • Class variables
  • Instance variables

In this article, we will focus specifically on instance variables in Java, including what they are, how they work, and why they matter. By the end, you’ll not only understand how to implement instance variables in Java but also know how they fit into the bigger picture of Java programming.
Here’s what we’ll cover:

Table of Contents:

Let’s begin!

What Is Instance Variable in Java?

“An instance variable in Java is simply a non-static variable that is declared inside a class but outside of any method, constructor, or block”.

Here’s the key thing to remember: every time you create an object of a class, Java gives that object its own copy of the instance variable.

That’s why it’s called an “instance” variable, as it belongs to the instance (object) of the class, not the class itself.

Syntax of Instance Variable in Java

Many learners often search for the exact syntax of instance variables in Java. It’s actually very straightforward:

class ClassName {
    type variableName; // instance variable
}

Here, type can be any valid data type (like int, String, or boolean), and variableName is the name you assign to your instance variable. You can declare an instance variable in Java as shown in the Oracle Java Documentation for classes and variables.

Now, you may be wondering, what exactly do we mean by an instance variable in Java?

Diagram of Instance Variable in Java

To better understand how instance variables work, let’s look at a simple diagram.

Diagram showing the lifecycle of instance variables in Java, from object creation to destruction.

Lifecycle of instance variable in java

Example of Instance Variables in Java

Whenever you create a new object of a class, you’re actually creating an instance of that class.

For example, imagine you have a class called STUDENT. In Java, every time a new STUDENT object is instantiated, it is allocated its own separate copies of the instance variables defined in the class.

class Student
{
    String studentName;
    int studentScore;
}

And if you create two STUDENT objects like,

Student student1 = new Student();
Student student2 = new Student();

Then, two separate Student objects will be created, each having its own set of instance variables. Now, think about it this way, each student will have their “own name” and “own score”, right?

This means that the values stored in studentName and studentScore are instance-specific, so each Student object will maintain its own separate values for these variables. Since these values change or vary from one object to another, we call them “variables”.

Each object (or instance) maintains its own copy of these variables, which is why Java calls them instance variables. Simple, isn’t it?

Now that you understand the meaning of instance variables and have seen an instance variable example in Java, let’s move one step further.

Video Thumbnail

Features of Instance Variables in Java

Here, we list the features of instance variables in Java programming to help you use them easily in your code. So, what are the features of instance variable in Java? Let’s break it down clearly:

  • The lifecycle of an instance variable depends on the object – it comes into existence when the object is created and ends when the object is destroyed.
  • Needs an object to use – You need an object to use instance variables, because you can access them only through the objects of the class.
  • Each object gets its own copy – Each object gets its own copy, as every object maintains separate values for its instance variables.
  • You don’t have to initialize an instance variable explicitly – Java automatically assigns a default value (for example, 0 for integers).
  • Declared inside a class, but outside methods – Instance variables are defined at the class level, but never inside a method, constructor, or block.
  • Visible across methods in a class – Once declared, instance variables can be accessed and used by multiple methods in the same class.
  • Access modifiers supported – They can be declared as private, public, protected, or with default visibility, depending on your design requirements.

After understanding these diagram and features, you might be thinking: “Alright, but how do I actually implement instance variables in Java?” Let’s explore that in the next section.

Get 100% Hike!

Master Most in Demand Skills Now!

How Do You Implement an Instance Variable in Java?

Implementing instance variables in Java is straightforward. The following simple code helps you understand the technical usage of instance variables in Java.

package intellipaat;
public class Student {

    // Instance variables
    public String studentName;
    private int studentScore;

    // Constructor to initialize student name
    public Student(String name) {
        this.studentName = name;
    }

    // Setter method for score
    public void setScore(int score) {
        this.studentScore = score;
    }

    // Method to print student details
    public void printDetails() {
        System.out.println("Name: " + studentName);
        System.out.println("Score: " + studentScore);
        System.out.println("----------------------");
    }

    // Main method to test
    public static void main(String[] args) {
        Student studentOne = new Student("Intellipaat Learner 1");
        Student studentTwo = new Student("Intellipaat Learner 2");
        Student studentThree = new Student("Intellipaat Learner 3");

        studentOne.setScore(92);
        studentTwo.setScore(85);
        studentThree.setScore(78);

        studentOne.printDetails();
        studentTwo.printDetails();
        studentThree.printDetails();
    }
}
Output:
Name: Intellipaat Learner 1
Score: 92
----------------------
Name: Intellipaat Learner 2
Score: 85
----------------------
Name: Intellipaat Learner 3
Score: 78
----------------------

Explanation:
In the above code, each Student object (studentOne, studentTwo, studentThree) holds its own values for studentName and studentScore. This means that even though all three belong to the same Student class, their data remains separate.

This instance variable in Java example demonstrates how each object maintains its own separate copy of the variables. That’s exactly what makes them “instance variables”, they are created when the object is created, and each object maintains its own copy.

How to Access Instance Variables in Java

In Java, instance variables can be accessed in two primary ways:

  • By using the this keyword
  • By using object references

Let’s go through each method in detail with examples.

1. Accessing Instance Variables with the this Keyword

The this keyword in Java refers to the current object of the class. It is particularly useful when constructor parameters or method parameters have the same name as instance variables.

class IntellipaatEmployee {
    String name;
    int age;
    
    // Constructor using 'this' keyword
    IntellipaatEmployee(String name, int age) {
        this.name = name;  // 'this' points to the instance variable
        this.age = age;    // avoids confusion with constructor parameters
    }
    
    void showDetails() {
        System.out.println("Employee Name: " + this.name + ", Age: " + this.age);
    }
}

public class Main {
    public static void main(String[] args) {
        IntellipaatEmployee emp = new IntellipaatEmployee("Ravi", 28);
        emp.showDetails();  // Output: Employee Name: Ravi, Age: 28
    }
}

Here, this.name and this.age make it clear that we’re referring to the instance variables of the class, not the constructor arguments.

2. Accessing Instance Variables with Object References

Another way to work with instance variables is through object references. When you create an object, the reference variable points to that object in memory. You can then access or modify instance variables using this reference.

class IntellipaatCourse {
    String courseName;
    int duration; // duration in weeks
    
    // Constructor
    IntellipaatCourse(String courseName, int duration) {
        this.courseName = courseName;
        this.duration = duration;
    }
    
    void displayCourse() {
        System.out.println("Course: " + courseName + ", Duration: " + duration + " weeks");
    }
}

public class Main {
    public static void main(String[] args) {
        IntellipaatCourse course1 = new IntellipaatCourse("Java Full Stack", 24);
        course1.displayCourse();  
        // Output: Course: Java Full Stack, Duration: 24 weeks
        
        IntellipaatCourse course2 = new IntellipaatCourse("Data Science", 20);
        course2.displayCourse();  
        // Output: Course: Data Science, Duration: 20 weeks
    }
}

In this case, course1 and course2 are object references that give us direct access to the instance variables courseName and duration.

When To Use Instance Variables in Java?

So, when should you prefer instance variables over local or class (static) variables? You should prefer instance variables over local or class (static) variables in situations like:

  • Each object needs to maintain its own state – for example, a student’s name, score, or age.
  • Data should remain specific to each object – unlike static variables, instance variables ensure values aren’t shared across all objects.
  • Variables need to be accessed by multiple methods in the same class – they persist for the lifetime of the object.
  • You need object-specific data storage – such as details of each student, employee, or product.

By using instance variables in Java, you can store object-specific information efficiently, making your code more organized, modular, and easier to maintain. This approach ensures each object retains its own state, which is essential in object-oriented programming.

Advantages of Instance Variables in Java

Instance variables in Java provide several benefits that make object-oriented programming more effective:

  • Higher encapsulation and object-specific data – Each object has its own copy of instance variables, allowing objects to maintain their own state independently.
  • Accessible across multiple methods – Instance variables can be used by any method in the class, making it easier to share data within the object.
  • Supports object-specific data storage – You can store details for each object, such as a student’s name, employee ID, or product details, separately.
  • Improves code organization – Tying data to specific objects makes your code more modular, readable, and maintainable.
  • Default initialization – Java automatically assigns default values to instance variables if you do not explicitly initialize them, reducing errors and simplifying code as described in the Java Language Specification.

Disadvantages of Instance Variables in Java

While instance variables in Java are very useful, they also come with certain drawbacks that developers should be aware of:

  • Higher memory consumption – Each object maintains its own copy of instance variables, so creating many objects can increase memory usage compared to static variables.
  • Slower access than local variables – Instance variables are stored on the heap, which can make access slightly slower than local variables stored on the stack.
  • Not shared across objects – If you need a value to be common for all objects, instance variables are unsuitable; static variables are better in such cases.
  • Lifecycle tied to the object – Instance variables exist only while the object exists. Losing all references to the object means losing the data.
  • Can increase program complexity – Managing multiple objects and their individual instance variables can make the code more complex.

Difference Between Instance Variable and Class Variable

To avoid any confusion, let’s quickly clear up the difference between instance variable and class variable in Java:

Difference Between Static and Instance Variable in Java:

Instance Variable Class Variable
Each object gets its own copy of the variable. Changes in one object do not affect others. Shared across all objects of the class. A change made through one object reflects in all.
Declared without the static keyword. Declared with the static keyword.
Accessed only through an object reference. Can be accessed using either the class name or an object reference.

Learn Java Programming With Intellipaat

𝐈𝐧𝐭𝐞𝐥𝐥𝐢𝐩𝐚𝐚𝐭 𝐅𝐫𝐞𝐞 𝐉𝐚𝐯𝐚 𝐂𝐨𝐮𝐫𝐬𝐞: This Free Java Course by Intellipaat is designed to help you master the fundamentals of Java programming from scratch. Whether you’re a beginner aiming to start your programming journey or preparing for interviews, this course covers all the essentials you need to build a strong foundation in Java.

What you’ll learn:

  • Java basics and syntax
  • OOPs concepts (Inheritance, Polymorphism, Encapsulation, Abstraction)
  • Arrays, Strings, and Collections
  • Exception Handling & Multithreading
  • File Handling and more!

Enroll now and start your Java learning journey completely free with Intellipaat Academy. Perfect for students, job seekers, and anyone preparing for Java certifications!

Ready to Master Java Programming? Take your Java skills to the next level with Intellipaat’s Java Programming Course.
Learn everything from the basics to advanced OOP concepts, work on hands-on projects, and become job-ready.
quiz-icon

Conclusion

In short, if you want each object to hold its own data, use instance variables.

With this, we have reached the end of Instance Variables in Java! By now, you should have a clear idea of what they are, how they work, and how they differ from class variables.

If you’re serious about building a career in Java or aiming for certifications, learning just the basics won’t be enough. You need structured training, real-world projects, and guidance from experts.

That’s where Intellipaat’s Java Training Course comes in. This program goes beyond the fundamentals, covering advanced concepts, hands-on projects, and industry-level use cases to make you job-ready.

Stay tuned as we continue exploring more interesting Java concepts in upcoming blogs!

About the Author

Software Developer | Technical Research Analyst Lead | Full Stack & Cloud Systems

Ayaan Alam is a skilled Software Developer and Technical Research Analyst Lead with 2 years of professional experience in Java, Python, and C++. With expertise in full-stack development, system design, and cloud computing, he consistently delivers high-quality, scalable solutions. Known for producing accurate and insightful technical content, Ayaan contributes valuable knowledge to the developer community.

Full Stack Developer Course Banner