Instance Variables in Java (with Examples)

When you declare non-static data fields or variables within a class but outside any method, constructor, or block, they are called instance variables in Java. These variables are also called non-static variables in Java because they are not defined with static keywords.

Instance variables are tied to individual objects (or instances) of the class, meaning each object of the class gets its own copy of these variables. Therefore, they can hold different values or data for each instance.

Instance variables in Java are used to define attributes (i.e. properties) or the state of a particular object. Since they are members of class, therefore, you can use them globally. These variables come into existence when you create an object (or instance) of the class. If you make any changes to data members, they do not affect data members of other objects.

Instance variables in Java

Syntax to Declare Instance Variables in Java

The general syntax to declare instance variables in Java within a class is as follows:

class ClassName {
    // Instance variable.
       DataType variableName;
}

Example 1: Let’s write a Java program based on the instance variables.

package myProgram;
public class Person {
  String name; // Instance variable.
  int age; // Instance variable.

// Declare a constructor.
  Person(String name, int age){
    this.name = name;
    this.age = age;
  }
// Declare an instance method.
  void display() {
	  System.out.println("Name: " +name);
	  System.out.println("Age: " +age);
  }
public static void main(String[] args) {
// Create an object of class Person and pass arguments to its constructor.
// First argument must be of string type and the second argument must be int type.	
   Person p = new Person("John", 25);
// Calling method using object reference variable.
   p.display();
  }
}
Output:
     Name: John
     Age: 25

Characteristics of Instance Variables in Java

There are the following characteristics of instance variables in Java that distinguish them from other types of variables, like static or local variables. They are:

  • We define instance variables directly within a class but outside of any methods, constructors, or blocks.
  • Each object of the class gets its own copy of the instance variables. So, any change in an instance variable of one object does not affect the instance variables of another object.
  • Instance variables in Java are accessed through objects of the class.
  • If you do not explicitly initialize instance variables in Java, the Java compiler automatically initializes them with their default values based on their data type.
  • Instance variables are accessible throughout the class where they are declared, provided they are not shadowed by local variables.
  • You can access them from all non-static methods and constructors of the class.
  • Unlike static variables, instance variables are specific to an object of the class. These variable do not share among all instances of the class.
  • When you create an instance variables within a class, it is allocated in the heap memory when an object is created.
  • When the object is destroyed (or when no references point to it), the memory is reclaimed by the garbage collector.
  • You can declare instance variables with access modifiers like public, private, protected, or default (package-private).
  • You cannot directly access instance variables in a static method or block because they belong to an object, not the class.
  • Instance variables can be shadowed by local variables with the same name. To refer to the instance variable explicitly, you can use the this keyword.

Basic Examples of Using Instance Variables

Let’s start with a basic example to understand the use of instance variables in Java programs.

Example 2: Let’s write a Java program in which we will declare instance variables and initialize them using object reference variables. This is the first way of initializing instance variables in Java.

package myProgram;
class Car {
   String model; // Instance variable.
   int year; // Instance variable.

// Declare an instance method.
   void displayDetails() {
      System.out.println("Model: " + model);
      System.out.println("Year: " + year);
   }
public static void main(String[] args) {
// Creating an object of class Car.
   Car c1 = new Car();
// Initializing instance variables using reference variable c1.
// Accessing instance variables through object reference variables.
   c1.model = "Tesla Model S";
   c1.year = 2023;

// Creating another object of class Car.
   Car c2 = new Car();
// Initializing instance variables using reference variable c2.
   c2.model = "Ford Mustang";
   c2.year = 2022;

// Calling the instance methods using reference variables c1 and c2.
   c1.displayDetails();
   c2.displayDetails();
  }
}
Output:
      Model: Tesla Model S
      Year: 2023
      Model: Ford Mustang
      Year: 2022

In this example, each object of the class Car has its own model and year, which demonstrate the instance-specific behavior of instance variables.

Example 3: Let’s write a Java program in which we will define instance variables and initialize them using constructor. This is the second way of initializing the instance variables in Java. We commonly use constructor to initialize instance variables when an object is created.

package myProgram;
class Employee {
   String name; // Instance variable of String type.
   int id; // Instance variable of int type.

// Declare a constructor to initialize instance variables with values.
   public Employee(String name, int id) {
      this.name = name;
      this.id = id;
   }
// Declare an instance method to display info.
   void displayInfo() {
       System.out.println("Employee ID: " + id);
       System.out.println("Employee Name: " + name);
   }
// Main method.
   public static void main(String[] args) {
  // Creating objects of class with passing argument values to its constructor.
     Employee emp1 = new Employee("Jane", 1012);
     Employee emp2 = new Employee("Bob", 1021);

  // Calling methods using reference variables emp1 and emp2.
     emp1.displayInfo();
     emp2.displayInfo();
  }
}
Output:
      Employee ID: 1012
      Employee Name: Jane
      Employee ID: 1021
      Employee Name: Bob

Shadowing of Instance Variables in Java

When you declare local variables with the same name as you declared instance variables with name, local variables will shadow instance variables in Java. To refer to the instance variable in such cases, we generally use the “this” keyword.

Example 4:

package myProgram;
class Rectangle {
   int length;
   int breadth;

  public Rectangle(int length, int breadth) {
        this.length = length; // Refers to the instance variable
        this.breadth = breadth; // Refers to the instance variable
  }

  int calculateArea() {
     return length * breadth;
  }

  public static void main(String[] args) {
     Rectangle rect = new Rectangle(5, 10);
     System.out.println("Area: " + rect.calculateArea());
  }
}
Output:
      Area: 50

Initialization of Instance Variables with Default Values

If you do not explicitly assign a value, Java automatically initializes instance variables to their default values. When you create an object of the class, JVM allocates memory for the instance variables of the class in the heap area. At this time, the JVM first assigns default values to the instance variables based on their data type.

When you explicitly initialize values to instance variables in Java, the JVM replaces the default values with the values you provide during the object creation or variable initialization.

Example 5:

package myProgram;
class Test {
// Instance variables
   int intValue;
   double doubleValue;
   char charValue;
   boolean booleanValue;
   String stringValue;

   void displayDefaultValues() {
        System.out.println("Default int value: " + intValue);
        System.out.println("Default double value: " + doubleValue);
        System.out.println("Default char value: '" + charValue + "'");
        System.out.println("Default boolean value: " + booleanValue);
        System.out.println("Default String value: " + stringValue);
   }
public static void main(String[] args) {
  Test t = new Test();
     t.displayDefaultValues();
    }
}
Output:
      Default int value: 0
      Default double value: 0.0
      Default char value: ''
      Default boolean value: false
      Default String value: null    

Difference between Local and Instance Variables

There are several differences between local and instance variables in Java that are as follows:

AspectLocal VariablesInstance Variables
DeclarationLocal variables are declared inside a method, constructor, or block.Instance variables are declared directly inside a class but outside any method, constructor, or block.
ScopeAccessible only within the method, constructor, or block in which these variables are declared.Accessible throughout the class, except in static method or static block.
LifetimeA local variable is created when the method, constructor, or block is invoked, and destroyed when it exits.An instance variable is created when an object of the class is instantiated and destroyed when the object is garbage collected.
Default InitializationYou must explicitly initialize local variables before using them, otherwise you will get error.Instance variables are automatically initialized with the default values by the JVM if you do not explicitly assigned them.
Memory LocationStored in the stack memory.Stored in the heap memory.
Object-SpecificNot tied to any specific object.Tied to a specific object of the class. Each object has its own copy.
Access ModifiersLocal variables cannot have access modifiers.Instance variables can be declared with access modifiers like private, protected, or public.
Keyword UsageThese variables cannot be accessed using this keyword.These variables can be accessed using the this keyword.

These are the basic differences between local variables and instance variables in Java that you should remember while working with variables.

Example 5: Demonstrating the Difference

class Test {
   int instanceVar = 100; // Instance variable

   void demonstrate() {
      int localVar = 10; // Local variable
      System.out.println("Local Variable: " + localVar);
      System.out.println("Instance Variable: " + instanceVar);
   }
public static void main(String[] args) {
  Test obj = new Test();
    obj.demonstrate();
  }
}
Output:
      Local Variable: 10
      Instance Variable: 100

Please Share Your Love.

6 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *