EMZETT.
Login

Objects

In short: A concrete instance of a class, created with the new keyword — carries its own values in the fields the class defines.

In more detail: Two objects of the same class are independent memory areas: changing a field of one leaves the other untouched (unless it’s a shared reference). Object variables in Java store a reference to the object on the heap, not the object itself.

Car myCar = new Car("Blue", 4);

In Depth

class Car {
    String color;
    int doors;
    Car(String color, int doors) { this.color = color; this.doors = doors; }
}
 
Car myCar = new Car("Blue", 4);
Car yourCar = new Car("Blue", 4); // different instance, same values
 
System.out.println(myCar == yourCar);        // false - two different objects in memory
System.out.println(myCar.color.equals(yourCar.color)); // true - content equal
 
myCar.color = "Red";
System.out.println(yourCar.color); // "Blue" - untouched, completely independent object

Every object created via new gets its own place on the heap at runtime, regardless of whether other objects of the same class carry identical field values — myCar and yourCar are two completely separate objects despite equal color/doors values, which the == comparison (reference comparison) correctly shows as false. An object variable like myCar doesn’t itself store the object, only a reference (simplified: a memory address) to it — copying the variable (Car copy = myCar;) only copies this reference, not the object behind it (see Non-primitive Types for the consequences of this).

References share an object

If you assign an existing object reference to a second variable, both variables afterwards point to the SAME object — a change via one variable is visible via the other, because there’s physically only one object in memory:

Car myCar = new Car("Blue", 4);
Car copy = myCar; // only copies the reference, NOT the object
 
copy.color = "Green";
System.out.println(myCar.color); // "Green" - same reference, same object!

This is one of the most common beginner stumbling blocks: copy “feels” like an independent copy, but is only a second name for exactly the same object. A true, independent copy needs either its own copy constructor (new Car(myCar.color, myCar.doors)) or a clone() implementation.

The lifecycle: creation, use, garbage collection

An object exists as long as at least one reference points to it. If you set the last reference to null or overwrite it (like copy = null;), the object becomes “reachable” for the garbage collector to remove — unlike languages with manual memory management (C/C++), Java doesn’t need delete/free to be called, the JVM automatically detects when an object is no longer reachable from any code, and frees the memory at some point.

See also: Classes, Constructors, OOP