Instance Variables and the `new` Keyword in Java: A Complete Guide

Published: (February 10, 2026 at 11:39 PM EST)
2 min read
Source: Dev.to

Source: Dev.to

Instance Variables

An instance variable is declared inside a class but outside any method, constructor, or block. It belongs to each specific object (instance) of the class, meaning every object gets its own copy.

  • Declared inside a class, outside methods.
  • Each object has a separate copy.
  • Receives default values (0 for int, null for objects, false for boolean).
  • Accessible through the object reference.
  • Stored in heap memory.
class Student {
    int marks;   // instance variable

    void display() {
        System.out.println("Marks: " + marks);
    }

    public static void main(String[] args) {
        Student s1 = new Student();
        Student s2 = new Student();

        s1.marks = 85;
        s2.marks = 90;

        s1.display(); // Marks: 85
        s2.display(); // Marks: 90
    }
}

In the example above, marks is an instance variable. Objects s1 and s2 each maintain their own value.

The new Keyword

The new keyword creates a new object of a class. When it is used, Java:

  1. Allocates memory for the object on the heap.
  2. Initializes instance variables with default values.
  3. Calls the class constructor.
  4. Returns a reference to the newly created object.
Student s = new Student();   // creates a new Student object
  • Student – class name.
  • s – reference variable that points to the new object.
  • new Student() – allocates memory and invokes the constructor.

Using new with Instance Variables

Instance variables come into existence only after an object is created with new. Without an object, they cannot be accessed.

Student s = new Student(); // object created
s.marks = 75;              // instance variable accessed

Summary

  • Instance variables store data specific to each object and reside in heap memory.
  • The new keyword is responsible for allocating that memory, initializing the variables, invoking the constructor, and providing a reference to the object.

Understanding these fundamentals is essential before moving on to more advanced Java topics such as constructors, inheritance, and overall object‑oriented design.

0 views
Back to Blog

Related posts

Read more »

Constructor

Constructor - The constructor name must be the same as the class name. - A constructor is a special method used to initialize instance variables when an object...

Java Inheritance

What is Inheritance? Inheritance is a mechanism where one class gets the states and behaviors of another class. It represents an is‑a relationship, meaning inh...