Instance Variables and the `new` Keyword in Java: A Complete Guide
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 (
0forint,nullfor objects,falseforboolean). - 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:
- Allocates memory for the object on the heap.
- Initializes instance variables with default values.
- Calls the class constructor.
- 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
newkeyword 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.