LearnContact
Lesson 1875 min read

Objects in Java

Learn what objects are in Java, how to create and initialize objects, access fields and methods, understand references, memory allocation, object identity, object relationships, garbage collection, and real-world object design.

Introduction

In the previous lesson, you learned that a class is a blueprint that defines data and behavior. A blueprint becomes useful when actual entities are created from it. In Java, these actual entities are called objects.

Class and Object
class Student {

    String name;

    int age;

    void study() {

        System.out.println(
                name + " is studying"
        );

    }

}


public class Main {

    public static void main(
        String[] args
    ) {

        Student student =
                new Student();

        student.name = "Aarav";

        student.age = 21;

        student.study();

    }

}

The Student class defines what student objects can contain and do. The new Student() expression creates an actual Student object in memory, while the student variable stores a reference to that object.

What You Will Learn
  • What an object is.
  • Why objects are needed.
  • The difference between a class and an object.
  • The three main characteristics of an object.
  • What object state means.
  • What object behavior means.
  • What object identity means.
  • How to create objects.
  • How the new keyword works.
  • What happens during object creation.
  • What reference variables are.
  • How objects are represented in memory.
  • The basic relationship between stack and heap memory.
  • How to access object fields.
  • How to update object fields.
  • How to call object methods.
  • How to create multiple objects.
  • Why each object has independent instance state.
  • How static state is shared.
  • What default object state is.
  • Different ways to initialize objects.
  • How field initialization works.
  • How method-based initialization works.
  • How constructor initialization works.
  • How object references work.
  • What happens during reference assignment.
  • How multiple references can point to one object.
  • How reference reassignment works.
  • What null references are.
  • Why NullPointerException occurs.
  • How to check references for null.
  • What anonymous objects are.
  • How objects are passed to methods.
  • How Java passes reference values.
  • How methods can modify objects.
  • Why reassigning a parameter does not reassign the caller variable.
  • How methods return objects.
  • How objects contain references to other objects.
  • How object relationships work.
  • What association is.
  • What aggregation is.
  • What composition is.
  • What object identity means.
  • The difference between reference equality and logical equality.
  • How the equals method works.
  • How the hashCode method works.
  • How the toString method works.
  • How the getClass method works.
  • Why every class inherits from Object.
  • Different forms of object copying.
  • The difference between reference copy, shallow copy, and deep copy.
  • What mutable objects are.
  • What immutable objects are.
  • The object lifecycle.
  • What reachable objects are.
  • What unreachable objects are.
  • How garbage collection works.
  • How objects become eligible for garbage collection.
  • What System.gc() actually means.
  • Why finalization should not be relied upon.
  • How arrays of objects work.
  • Why an object array initially contains null references.
  • How to create and iterate through object arrays.
  • How Strings and wrapper classes are objects.
  • What method chaining is.
  • What fluent objects are.
  • What temporary objects are.
  • What object ownership means.
  • Why defensive copying is useful.
  • How to create real-world object models.
  • Common object-related errors.
  • Best practices for working with objects.

What is an Object?

An object is a runtime instance of a class. It occupies memory and contains its own instance state while providing access to the behavior defined by its class.

Create an Object
Student student =
        new Student();
Object Concept
CLASS

Student

Defines:

name
age
study()


        │
        │ CREATE OBJECT
        ▼


OBJECT

┌─────────────────────────┐
│ Student Object          │
│                         │
│ name = "Aarav"          │
│ age = 21                │
│                         │
│ Can perform study()     │
└─────────────────────────┘
Object Definition
  • An object is an instance of a class.
  • An object exists at runtime.
  • An object occupies memory.
  • An object has state.
  • An object has behavior.
  • An object has identity.
  • An object is accessed through a reference.
  • Multiple objects can be created from one class.

Why Objects are Needed

Real Entities

Objects represent actual entities such as students, products, accounts, employees, and orders.

State Storage

Each object can store its own values through instance fields.

Behavior

Objects perform operations through methods defined by their classes.

Modularity

Applications can be built from independent objects that work together.

Reusability

Many objects can be created from one reusable class definition.

Controlled State

Objects can protect and manage their state through methods and access modifiers.

Real-World Analogy

Think of a class as a blueprint for a house and objects as actual houses built from that blueprint.

House Analogy
HOUSE BLUEPRINT

┌─────────────────────────┐
│ 3 Bedrooms              │
│ 2 Bathrooms             │
│ 1 Kitchen               │
└─────────────────────────┘

          │
          │ BUILD
          ▼

┌─────────────────┐
│ HOUSE OBJECT 1  │
│                 │
│ Color: White    │
│ Owner: Aarav    │
└─────────────────┘

┌─────────────────┐
│ HOUSE OBJECT 2  │
│                 │
│ Color: Blue     │
│ Owner: Meera    │
└─────────────────┘

SAME BLUEPRINT

DIFFERENT ACTUAL HOUSES

DIFFERENT STATE

DIFFERENT IDENTITY

Class vs Object

Comparison
CLASS

Blueprint or definition

Defines structure

Defines behavior

Creates a new type

Does not represent one specific entity


OBJECT

Runtime instance of a class

Contains actual state

Uses class behavior

Occupies runtime memory

Represents one specific entity
Class and Objects
class Car {

    String brand;

    int speed;

}


Car firstCar =
        new Car();

Car secondCar =
        new Car();
One Class Many Objects
              CAR CLASS

                  │
          ┌───────┼───────┐
          │       │       │
          ▼       ▼       ▼

       OBJECT 1 OBJECT 2 OBJECT 3

Object Characteristics

Three Characteristics
EVERY OBJECT HAS

┌─────────────────────┐
│ STATE               │
│                     │
│ What data it holds  │
└─────────────────────┘

┌─────────────────────┐
│ BEHAVIOR            │
│                     │
│ What it can do      │
└─────────────────────┘

┌─────────────────────┐
│ IDENTITY            │
│                     │
│ Which object it is  │
└─────────────────────┘

State

The state of an object is represented by the current values stored in its instance fields.

Object State
class Car {

    String brand;

    String color;

    int speed;

}
Car State
CAR OBJECT STATE

brand = "Toyota"

color = "Black"

speed = 80

The state of an object can change during program execution unless the object is designed to be immutable.

Behavior

Behavior represents the actions an object can perform through its instance methods.

Object Behavior
class Car {

    int speed;

    void accelerate() {

        speed += 10;

    }

    void brake() {

        speed -= 10;

    }

}
Behavior Changes State
CURRENT STATE

speed = 50

      │
      │ accelerate()
      ▼

NEW STATE

speed = 60

Identity

Identity distinguishes one object from another, even when two objects contain exactly the same field values.

Different Objects
Student first =
        new Student();

Student second =
        new Student();
Different Identity
FIRST REFERENCE              SECOND REFERENCE

      │                             │
      ▼                             ▼

┌──────────────┐             ┌──────────────┐
│ Student      │             │ Student      │
│ Object A     │             │ Object B     │
└──────────────┘             └──────────────┘

DIFFERENT OBJECTS

EVEN IF FIELD VALUES ARE IDENTICAL

Creating Objects

Object Creation Syntax
ClassName referenceName =
        new ClassName();
Student Object
Student student =
        new Student();
Expression Parts
Student student = new Student();

   │       │       │      │
   │       │       │      └── Constructor Call
   │       │       │
   │       │       └───────── Creates Object
   │       │
   │       └───────────────── Reference Variable
   │
   └───────────────────────── Reference Type

The new Keyword

The new keyword creates a new object at runtime and returns a reference to that object.

Using new
new Student();
new Operation
new Student()

      │
      ▼

ALLOCATE MEMORY

      │
      ▼

INITIALIZE OBJECT

      │
      ▼

RUN CONSTRUCTOR

      │
      ▼

RETURN REFERENCE

Object Creation Process

Create Object
Student student =
        new Student();
Simplified Creation Process
STEP 1

Student type is available


STEP 2

new requests object creation


STEP 3

Memory is allocated


STEP 4

Fields receive default values


STEP 5

Explicit field initializers run


STEP 6

Instance initialization blocks run


STEP 7

Constructor body runs


STEP 8

Reference to object is returned


STEP 9

Reference is assigned to student
Simplified Process
  • The exact JVM implementation contains additional technical details.
  • The important idea is that memory is allocated, state is initialized, the constructor runs, and a reference is returned.
  • Inheritance affects the complete initialization sequence and will be covered later.

Reference Variables

A reference variable stores a reference to an object. It does not directly contain the complete object.

Reference Variable
Student student =
        new Student();
Reference Model
REFERENCE VARIABLE

student

┌──────────────┐
│ Reference    │
└──────┬───────┘
       │
       │ POINTS TO
       ▼

┌────────────────────┐
│ Student Object     │
│                    │
│ name               │
│ age                │
└────────────────────┘

Object Memory

Objects are generally allocated in heap memory. Variables that hold references may exist in different places depending on whether they are local variables, fields, array elements, or other runtime structures.

Simplified Memory Model
HEAP MEMORY

┌─────────────────────────┐
│ Student Object          │
│                         │
│ name = null             │
│ age = 0                 │
└─────────────────────────┘


REFERENCE

student

      │
      └──────────────► Student Object

Stack and Heap

Local Reference
public static void main(
    String[] args
) {

    Student student =
            new Student();

}
Beginner Memory Model
STACK                         HEAP

main() frame

┌──────────────┐             ┌─────────────────┐
│ student      │────────────►│ Student Object  │
│ reference    │             │                 │
└──────────────┘             │ name = null     │
                             │ age = 0         │
                             └─────────────────┘
Important Simplification
  • Objects are generally allocated on the heap.
  • Local variables belong to method execution frames.
  • A local reference variable can point to an object.
  • The reference and the object are different things.
  • Actual JVM optimizations can be more complex than this beginner model.

Accessing Object Fields

Access Fields
class Student {

    String name;

    int age;

}


Student student =
        new Student();

student.name = "Aarav";

student.age = 21;

System.out.println(
        student.name
);

System.out.println(
        student.age
);
Field Access
reference.field

student.name

student.age

Updating Object Fields

Update State
Student student =
        new Student();

student.name = "Aarav";

student.age = 21;


student.age = 22;
State Change
BEFORE

age = 21

    │
    │ student.age = 22;
    ▼

AFTER

age = 22

Calling Object Methods

Call Method
class Student {

    String name;

    void study() {

        System.out.println(
                name + " is studying"
        );

    }

}


Student student =
        new Student();

student.name = "Aarav";

student.study();
Method Call
reference.method()

student.study()

Creating Multiple Objects

Multiple Objects
Student first =
        new Student();

Student second =
        new Student();

Student third =
        new Student();
Three Objects
first ─────────► OBJECT 1

second ────────► OBJECT 2

third ─────────► OBJECT 3


SAME CLASS

THREE DIFFERENT OBJECTS

Independent Object State

Independent State
Student first =
        new Student();

first.name = "Aarav";

first.age = 21;


Student second =
        new Student();

second.name = "Meera";

second.age = 24;
Separate State
FIRST OBJECT

name = "Aarav"

age = 21


SECOND OBJECT

name = "Meera"

age = 24


CHANGING FIRST OBJECT

DOES NOT AUTOMATICALLY CHANGE

SECOND OBJECT

Shared Static State

Static and Instance State
class Student {

    static String college =
            "PrograMinds Academy";

    String name;

}
Shared and Independent Data
CLASS LEVEL

college = "PrograMinds Academy"

          ▲
          │
        SHARED
          │

┌─────────────────┐
│ OBJECT 1        │
│ name = "Aarav"  │
└─────────────────┘

┌─────────────────┐
│ OBJECT 2        │
│ name = "Meera"  │
└─────────────────┘


name

DIFFERENT FOR EACH OBJECT


college

SHARED AT CLASS LEVEL

Default Object State

Default State
class Student {

    String name;

    int age;

    double marks;

    boolean active;

}


Student student =
        new Student();
Initial Values
student.name

null


student.age

0


student.marks

0.0


student.active

false

Object Initialization

Object initialization means giving meaningful starting values to the state of an object.

Initialization Methods
OBJECT INITIALIZATION

├── Field Initializers
│
├── Direct Field Assignment
│
├── Methods
│
├── Initialization Blocks
│
└── Constructors

Field Initialization

Field Initializers
class Student {

    String name = "Unknown";

    int age = 18;

    boolean active = true;

}

Every newly created Student object starts with these explicitly initialized values unless later initialization changes them.

Method-Based Initialization

Initialize with Method
class Student {

    String name;

    int age;


    void setDetails(
        String studentName,
        int studentAge
    ) {

        name = studentName;

        age = studentAge;

    }

}


Student student =
        new Student();

student.setDetails(
        "Aarav",
        21
);

Constructor Initialization

Constructor Initialization
class Student {

    String name;

    int age;


    Student(
        String name,
        int age
    ) {

        this.name = name;

        this.age = age;

    }

}


Student student =
        new Student(
            "Aarav",
            21
        );

Constructors provide one of the most important ways to initialize objects. They are covered completely in the next lesson.

Object References

Java code normally interacts with objects through references. A reference identifies an object that can be accessed.

Object Reference
Student student =
        new Student();
Reference Relationship
student

REFERENCE VARIABLE

      │
      │ HOLDS REFERENCE TO
      ▼

STUDENT OBJECT

Reference Assignment

Assign Reference
Student first =
        new Student();

Student second =
        first;

This does not create a second Student object. The reference value stored in first is copied into second.

Same Object
first ───────┐
              │
              ▼
        ┌──────────────┐
        │ Student      │
        │ Object       │
        └──────────────┘
              ▲
              │
second ───────┘


TWO REFERENCES

ONE OBJECT

Multiple References to One Object

Shared Object
Student first =
        new Student();

first.name = "Aarav";


Student second =
        first;

second.name = "Meera";


System.out.println(
        first.name
);
Output
Meera

Both references point to the same object. Changing the object through second is visible when the same object is accessed through first.

Reference Reassignment

Reassign Reference
Student student =
        new Student();

student =
        new Student();
Reassignment
BEFORE

student ─────► OBJECT A


AFTER

student ─────► OBJECT B


OBJECT A

No longer referenced by student

null References

null Reference
Student student = null;
null Meaning
student

   │
   ▼

null


NO STUDENT OBJECT

IS REFERENCED
What null Means
  • The variable has a reference type.
  • The variable currently does not refer to an object.
  • null is not an object.
  • null can be assigned to reference variables.
  • null cannot be assigned to primitive variables.

NullPointerException

Invalid Object Access
Student student = null;

student.name = "Aarav";

This causes NullPointerException because there is no Student object through which the name field can be accessed.

Problem
student

   │
   ▼

null

   │
   │ student.name
   ▼

NO OBJECT EXISTS

NullPointerException

Checking for null

Null Check
if (student != null) {

    student.study();

}
Check for Missing Object
if (student == null) {

    System.out.println(
            "Student not found"
    );

}
Do Not Add Null Checks Everywhere
  • Use null checks when absence is genuinely possible.
  • Design objects so required values are initialized correctly.
  • Validate external input.
  • Avoid hiding programming errors with unnecessary checks.
  • Modern Java applications may also use Optional in appropriate APIs.

Anonymous Objects

Anonymous Object
new Student().study();
Comparison
NAMED REFERENCE

Student student =
        new Student();

student.study();


ANONYMOUS OBJECT

new Student().study();

An anonymous object is useful when an object is needed only for a single immediate operation and no later reference is required.

Objects as Method Arguments

Pass Object
class Student {

    String name;

}


static void showStudent(
    Student student
) {

    System.out.println(
            student.name
    );

}


Student student =
        new Student();

student.name = "Aarav";

showStudent(student);

Reference Passing

Java is always pass-by-value. When an object is passed to a method, the value being copied is the object reference.

Reference Value Copy
CALLER

student reference

      │
      │ COPY REFERENCE VALUE
      ▼

METHOD PARAMETER

student reference

      │
      ▼

SAME OBJECT
Important Java Rule
  • Java is always pass-by-value.
  • Primitive values are copied.
  • Reference values are also copied.
  • The copied reference can point to the same object.
  • This is not pass-by-reference.

Modifying Objects Inside Methods

Modify Object
static void rename(
    Student student
) {

    student.name = "Meera";

}


Student student =
        new Student();

student.name = "Aarav";

rename(student);


System.out.println(
        student.name
);
Output
Meera

The method receives a copied reference that points to the same object, so it can modify that object.

Reassigning Object Parameters

Parameter Reassignment
static void replace(
    Student student
) {

    student =
            new Student();

    student.name = "Meera";

}


Student original =
        new Student();

original.name = "Aarav";

replace(original);


System.out.println(
        original.name
);
Output
Aarav

Reassigning the method parameter changes only the local copy of the reference. It does not reassign the original variable in the caller.

Returning Objects from Methods

Return Object
static Student createStudent() {

    Student student =
            new Student();

    student.name = "Aarav";

    student.age = 21;

    return student;

}


Student student =
        createStudent();

A method can return a reference to an object just as it can return primitive values.

Objects Inside Objects

Object Reference Field
class Address {

    String city;

    String country;

}


class Student {

    String name;

    Address address;

}
Connect Objects
Address address =
        new Address();

address.city = "Mumbai";

address.country = "India";


Student student =
        new Student();

student.name = "Aarav";

student.address = address;
Object Graph
student

   │
   ▼

┌───────────────────┐
│ Student Object    │
│                   │
│ name = "Aarav"    │
│ address ──────────┼─────┐
└───────────────────┘     │
                          ▼
                  ┌────────────────┐
                  │ Address Object │
                  │                │
                  │ city           │
                  │ country        │
                  └────────────────┘

Object Relationships

Objects rarely exist alone in real applications. They collaborate and form relationships with other objects.

Common Relationships
OBJECT RELATIONSHIPS

├── Association
│
├── Aggregation
│
└── Composition

Association

Association
class Teacher {

    void teach(Student student) {

        System.out.println(
                "Teaching "
                + student.name
        );

    }

}

Association represents a general interaction between independent objects.

Aggregation

Aggregation
class Employee {

    String name;

}


class Department {

    Employee employee;

}

In aggregation, one object contains a reference to another object that can exist independently.

Independent Lifecycles
DEPARTMENT OBJECT

      │
      │ HAS
      ▼

EMPLOYEE OBJECT


EMPLOYEE CAN EXIST

WITHOUT THAT DEPARTMENT OBJECT

Composition

Composition
class Engine {

    void start() {

        System.out.println(
                "Engine started"
        );

    }

}


class Car {

    private Engine engine =
            new Engine();

    void start() {

        engine.start();

    }

}

Composition represents strong ownership. The containing object controls the creation and lifecycle relationship of its internal part.

Object Identity

Two Objects
Student first =
        new Student();

Student second =
        new Student();

first.name = "Aarav";

second.name = "Aarav";

Although the field values are identical, first and second still refer to two different objects with different identities.

Reference Equality

For reference types, the == operator checks whether two references point to the same object.

Reference Equality
Student first =
        new Student();

Student second =
        new Student();

Student third =
        first;


System.out.println(
        first == second
);

System.out.println(
        first == third
);
Output
false

true

Logical Equality

Logical equality asks whether two objects should be considered equal based on their meaningful content rather than whether they are the same object.

Identity vs Content
OBJECT A

name = "Aarav"
age = 21


OBJECT B

name = "Aarav"
age = 21


SAME IDENTITY?

NO


SAME LOGICAL CONTENT?

POSSIBLY YES

The equals Method

The equals method is used to define logical equality. The default implementation inherited from Object behaves like identity comparison unless a class overrides it.

Default equals
Student first =
        new Student();

Student second =
        new Student();


System.out.println(
        first.equals(second)
);
Logical Equality
  • Classes can override equals to compare meaningful state.
  • String overrides equals to compare character content.
  • Custom classes should follow the equals contract.
  • When equals is overridden, hashCode should also be overridden consistently.

The hashCode Method

The hashCode method returns an integer hash value used heavily by hash-based collections such as HashMap and HashSet.

Hash Code
Student student =
        new Student();

int hash =
        student.hashCode();

System.out.println(hash);
equals and hashCode Contract
  • Equal objects must produce the same hash code.
  • Unequal objects may still produce the same hash code.
  • Override equals and hashCode together when defining logical equality.
  • Do not use hash codes as permanent unique object identifiers.

The toString Method

The toString method returns a textual representation of an object.

Default toString
Student student =
        new Student();

System.out.println(student);

The default representation is usually not useful for business information, so classes often override toString.

Override toString
class Student {

    String name;

    int age;


    @Override
    public String toString() {

        return "Student{name='"
                + name
                + "', age="
                + age
                + "}";

    }

}

The getClass Method

Runtime Class
Student student =
        new Student();

System.out.println(
        student.getClass()
);

System.out.println(
        student.getClass()
               .getName()
);

The getClass method returns runtime type information represented by a Class object.

The Object Class

java.lang.Object is the root class of the Java class hierarchy. Every Java class directly or indirectly inherits from Object.

Object Hierarchy
java.lang.Object

        │
        ├── Student
        │
        ├── Employee
        │
        ├── Product
        │
        ├── String
        │
        └── Other Classes
Important Object Methods
  • equals()
  • hashCode()
  • toString()
  • getClass()
  • Other low-level methods also exist in Object.

Object Copying

Object copying can mean different things. It is important to distinguish copying a reference from creating a new object with copied state.

Copying Types
OBJECT COPYING

├── Reference Copy
│
├── Manual Object Copy
│
├── Shallow Copy
│
└── Deep Copy

Reference Copy

Reference Copy
Student first =
        new Student();

Student second =
        first;

No new Student object is created. Both variables refer to the same object.

Manual Object Copy

Copy Fields
Student first =
        new Student();

first.name = "Aarav";

first.age = 21;


Student second =
        new Student();

second.name = first.name;

second.age = first.age;

Now two different Student objects exist with copied field values.

Shallow Copy

A shallow copy creates a new outer object but copies references to nested mutable objects.

Shallow Copy
ORIGINAL OBJECT

┌──────────────────┐
│ Student A        │
│ address ─────────┼────┐
└──────────────────┘    │
                        ▼
                 ┌──────────────┐
                 │ Address      │
                 │ Object       │
                 └──────────────┘
                        ▲
                        │
┌──────────────────┐    │
│ Student B        │    │
│ address ─────────┼────┘
└──────────────────┘


TWO OUTER OBJECTS

ONE SHARED NESTED OBJECT

Deep Copy

A deep copy creates independent copies of the outer object and the relevant nested mutable objects.

Deep Copy
STUDENT A

┌──────────────────┐
│ address ─────────┼────► ADDRESS A
└──────────────────┘


STUDENT B

┌──────────────────┐
│ address ─────────┼────► ADDRESS B
└──────────────────┘


INDEPENDENT OUTER OBJECTS

INDEPENDENT NESTED OBJECTS

Mutable Objects

A mutable object allows its internal state to change after creation.

Mutable Object
class BankAccount {

    private double balance;


    void deposit(double amount) {

        balance += amount;

    }

}
State Changes
INITIAL STATE

balance = 1000


deposit(500)


NEW STATE

balance = 1500

Immutable Objects

An immutable object does not allow its observable state to change after creation.

Immutable Object
final class User {

    private final String name;


    User(String name) {

        this.name = name;

    }


    String getName() {

        return name;

    }

}
Benefits of Immutability
  • State is easier to reason about.
  • Objects are safer to share.
  • Unexpected modifications are reduced.
  • Thread-safe designs can become easier.
  • Immutable objects work well as value objects.

Object Lifecycle

Lifecycle
1. CLASS AVAILABLE

        │
        ▼

2. OBJECT CREATED

        │
        ▼

3. OBJECT INITIALIZED

        │
        ▼

4. OBJECT USED

        │
        ▼

5. OBJECT BECOMES UNREACHABLE

        │
        ▼

6. ELIGIBLE FOR GARBAGE COLLECTION

        │
        ▼

7. MEMORY MAY BE RECLAIMED

Reachable Objects

An object is reachable when it can still be accessed through a chain of references from active program roots.

Reachable Object
ACTIVE REFERENCE

student

   │
   ▼

STUDENT OBJECT


OBJECT IS REACHABLE

Unreachable Objects

Object Becomes Unreachable
Student student =
        new Student();

student = null;
Unreachable Object
BEFORE

student ─────► OBJECT


AFTER

student ─────► null


OBJECT

NO LONGER REACHABLE

THROUGH THAT REFERENCE

Garbage Collection

Garbage collection is the JVM process that automatically identifies unreachable objects and may reclaim the memory they occupy.

Garbage Collection Concept
REACHABLE OBJECT

Still in use

Memory retained


UNREACHABLE OBJECT

No longer accessible

Eligible for garbage collection


GARBAGE COLLECTOR

May reclaim memory
Important
  • You do not manually free normal Java objects.
  • An unreachable object becomes eligible for garbage collection.
  • Eligibility does not mean immediate collection.
  • The JVM decides when garbage collection occurs.
  • Garbage collection manages memory, not all external resources.

Making Objects Eligible for Garbage Collection

Set Reference to null
Student student =
        new Student();

student = null;
Reassign Reference
Student student =
        new Student();

student =
        new Student();
Local Scope Ends
static void createStudent() {

    Student student =
            new Student();

}

When no reachable reference path remains, an object becomes eligible for garbage collection.

System.gc()

Request Garbage Collection
System.gc();

System.gc() requests that the JVM consider running garbage collection. It does not guarantee that garbage collection will run immediately.

Do Not Depend on System.gc()
  • It is only a request.
  • The JVM controls garbage collection.
  • Application correctness must not depend on immediate garbage collection.
  • Normal applications rarely need to call System.gc() directly.

Object Finalization

Older Java code sometimes used the finalize method for cleanup before garbage collection. Finalization is deprecated and should not be used for modern resource management.

Modern Resource Management
  • Do not rely on finalize.
  • Use try-with-resources for AutoCloseable resources.
  • Close files, streams, sockets, and database resources explicitly.
  • Garbage collection manages memory, not deterministic resource cleanup.

Object Arrays

An array can store references to objects of a compatible type.

Object Array
Student[] students =
        new Student[3];
Initial Array
students

┌─────────┬─────────┬─────────┐
│  null   │  null   │  null   │
└─────────┴─────────┴─────────┘

Array of References

Creating an object array creates the array structure, not the individual objects stored in its elements.

Only Array Created
Student[] students =
        new Student[3];
Common Mistake
  • The array exists.
  • The Student objects do not yet exist.
  • Each element initially contains null.
  • Create each Student object separately.

Creating Objects in an Array

Populate Object Array
Student[] students =
        new Student[3];


students[0] =
        new Student();

students[1] =
        new Student();

students[2] =
        new Student();


students[0].name = "Aarav";

students[1].name = "Meera";

students[2].name = "Kabir";
Array and Objects
ARRAY

┌─────────┬─────────┬─────────┐
│ ref 1   │ ref 2   │ ref 3   │
└────┬────┴────┬────┴────┬────┘
     │         │         │
     ▼         ▼         ▼

 OBJECT 1   OBJECT 2   OBJECT 3

Iterating Object Arrays

Enhanced for Loop
for (Student student : students) {

    System.out.println(
            student.name
    );

}
Traditional for Loop
for (
    int index = 0;
    index < students.length;
    index++
) {

    System.out.println(
            students[index].name
    );

}

Objects and Strings

String is a class, so every String value is an object.

String Objects
String first =
        "Java";

String second =
        new String("Java");
String is Special
  • String is a class.
  • String objects are immutable.
  • String literals can use the String pool.
  • Strings support methods like length, substring, and equals.
  • String behavior was covered in the previous lesson.

Objects and Wrapper Classes

Primitive and Wrapper
int number = 10;

Integer objectNumber = 10;
Primitive Wrappers
PRIMITIVE       WRAPPER CLASS

byte            Byte

short           Short

int             Integer

long            Long

float           Float

double          Double

char            Character

boolean         Boolean

Wrapper classes allow primitive-like values to participate in APIs and collections that work with objects.

Method Chaining

Method chaining occurs when one method returns an object reference that is immediately used to call another method.

Method Chaining
class Builder {

    Builder setName(
        String name
    ) {

        System.out.println(name);

        return this;

    }


    Builder setAge(
        int age
    ) {

        System.out.println(age);

        return this;

    }

}


new Builder()
        .setName("Aarav")
        .setAge(21);

Fluent Objects

A fluent API is designed so that method calls read naturally and can often be chained.

Fluent Style
Student student =
        new Student()
            .setName("Aarav")
            .setAge(21)
            .setActive(true);
Fluent Design
  • Methods commonly return this.
  • Calls can be chained.
  • Readable configuration APIs can be created.
  • Do not use chaining when it makes code harder to understand.

Temporary Objects

Temporary Object
System.out.println(
        new Student()
);

A temporary object is created for immediate use without keeping a long-lived named reference.

Object Ownership

Object ownership describes which object or component is responsible for creating, managing, and controlling another object.

Ownership Questions
WHO CREATES THE OBJECT?

WHO STORES THE REFERENCE?

WHO MODIFIES THE OBJECT?

WHO SHARES THE OBJECT?

CAN THE OBJECT EXIST INDEPENDENTLY?

SHOULD THE OBJECT BE MUTABLE?

WHO CONTROLS ITS LIFECYCLE?

Defensive Copying

Defensive copying protects internal mutable state by returning or storing copies instead of directly sharing mutable objects.

Defensive Copy Concept
class Student {

    private Address address;


    Student(Address address) {

        this.address =
                new Address(address);

    }


    Address getAddress() {

        return new Address(address);

    }

}
Why Defensive Copying Matters
  • Prevents unexpected external modification.
  • Protects encapsulated mutable state.
  • Supports safer immutable designs.
  • Is especially important when working with mutable collections and nested objects.

Real-World Student Object

Student Objects
class Student {

    String name;

    int age;

    double marks;


    void study() {

        System.out.println(
                name + " is studying"
        );

    }


    boolean hasPassed() {

        return marks >= 40;

    }

}


public class Main {

    public static void main(
        String[] args
    ) {

        Student first =
                new Student();

        first.name = "Aarav";

        first.age = 21;

        first.marks = 82.5;


        Student second =
                new Student();

        second.name = "Meera";

        second.age = 22;

        second.marks = 91.0;


        first.study();

        second.study();


        System.out.println(
                first.hasPassed()
        );

        System.out.println(
                second.hasPassed()
        );

    }

}

Bank Account Objects

BankAccount Objects
class BankAccount {

    String accountNumber;

    double balance;


    void deposit(double amount) {

        if (amount > 0) {

            balance += amount;

        }

    }


    void withdraw(double amount) {

        if (
            amount > 0
            && amount <= balance
        ) {

            balance -= amount;

        }

    }

}


BankAccount first =
        new BankAccount();

first.accountNumber =
        "ACC101";

first.balance = 5000;


BankAccount second =
        new BankAccount();

second.accountNumber =
        "ACC102";

second.balance = 10000;


first.deposit(2000);

second.withdraw(3000);

Product Objects

Product Objects
class Product {

    String name;

    double price;

    int quantity;


    double calculateTotal() {

        return price * quantity;

    }

}


Product laptop =
        new Product();

laptop.name = "Laptop";

laptop.price = 75000;

laptop.quantity = 2;


Product mouse =
        new Product();

mouse.name = "Mouse";

mouse.price = 1200;

mouse.quantity = 5;


System.out.println(
        laptop.calculateTotal()
);

System.out.println(
        mouse.calculateTotal()
);

Employee Objects

Employee Objects
class Employee {

    static String company =
            "PrograMinds";

    String name;

    double monthlySalary;


    double annualSalary() {

        return monthlySalary * 12;

    }

}


Employee first =
        new Employee();

first.name = "Aarav";

first.monthlySalary = 50000;


Employee second =
        new Employee();

second.name = "Meera";

second.monthlySalary = 70000;


System.out.println(
        first.name
);

System.out.println(
        first.annualSalary()
);

System.out.println(
        Employee.company
);

Order Object Model

Related Objects
class Customer {

    String name;

}


class Product {

    String name;

    double price;

}


class Order {

    Customer customer;

    Product product;

    int quantity;


    double calculateTotal() {

        return product.price
                * quantity;

    }

}
Create Object Model
Customer customer =
        new Customer();

customer.name = "Aarav";


Product product =
        new Product();

product.name = "Laptop";

product.price = 75000;


Order order =
        new Order();

order.customer = customer;

order.product = product;

order.quantity = 2;


System.out.println(
        order.calculateTotal()
);
Object Graph
ORDER OBJECT

├── customer ─────► CUSTOMER OBJECT
│
├── product ──────► PRODUCT OBJECT
│
└── quantity = 2

Object Design Process

Design Process
STEP 1

IDENTIFY REAL CONCEPTS

Student
Course
Teacher


STEP 2

IDENTIFY OBJECT STATE

Student:

name
age
marks


STEP 3

IDENTIFY OBJECT BEHAVIOR

study()
takeExam()
showResult()


STEP 4

IDENTIFY RELATIONSHIPS

Student enrolls in Course

Teacher teaches Course


STEP 5

IDENTIFY OWNERSHIP

Who creates objects?

Who stores references?

Who controls lifecycle?


STEP 6

CONTROL MUTABILITY

What can change?

What must never change?


STEP 7

PROTECT STATE

Use access modifiers

Use validation

Avoid unnecessary exposure


STEP 8

CREATE AND TEST OBJECTS

Valid state

Invalid state

Multiple objects

Shared references

null scenarios

Common Object Errors

Common Errors
OBJECT ERRORS

├── Confusing Class and Object
├── Thinking Class is an Object
├── Thinking Object is a Class
├── Forgetting new Keyword
├── Forgetting to Create an Object
├── Declaring Reference Without Object Creation
├── Accessing Members Through null
├── Causing NullPointerException
├── Forgetting null Checks When Absence is Valid
├── Adding Unnecessary null Checks Everywhere
├── Confusing Reference and Object
├── Thinking Reference Stores Complete Object
├── Assuming Reference Assignment Copies Object
├── Accidentally Sharing One Mutable Object
├── Modifying Object Through Another Reference
├── Forgetting Multiple References Can Point to One Object
├── Losing a Reference Through Reassignment
├── Expecting Reassignment to Modify Caller Reference
├── Saying Java is Pass-by-Reference
├── Forgetting Java is Pass-by-Value
├── Misunderstanding Copied Reference Values
├── Comparing Objects with == for Logical Equality
├── Forgetting == Checks Reference Identity
├── Incorrect equals Implementation
├── Overriding equals Without hashCode
├── Using Mutable Fields Carelessly in hashCode
├── Relying on Default toString for Useful Output
├── Using Hash Code as Unique Identity
├── Confusing Object Identity with Logical Equality
├── Creating Object Array Without Creating Elements
├── Accessing null Array Elements
├── Forgetting Object Arrays Store References
├── Accidentally Creating Shallow Copies
├── Expecting Reference Copy to Create New Object
├── Sharing Nested Mutable Objects Unintentionally
├── Incorrect Deep Copy Logic
├── Exposing Mutable Internal Objects
├── Forgetting Defensive Copies
├── Making Everything Mutable
├── Making Everything Immutable Without Need
├── Incorrect Object Ownership
├── Circular Object References Without Clear Design
├── Creating Too Many Temporary Objects
├── Premature Memory Optimization
├── Calling System.gc() Unnecessarily
├── Expecting Immediate Garbage Collection
├── Relying on finalize
├── Using Garbage Collection for Resource Cleanup
├── Forgetting to Close External Resources
├── Misunderstanding Reachability
├── Assuming null Immediately Deletes Object
├── Assuming Unreachable Means Immediately Collected
├── Creating Anonymous Objects When Later Access is Needed
├── Excessive Method Chaining
├── Returning this Without Clear Fluent Design
├── Exposing Public Mutable Fields
├── Allowing Invalid Object State
├── Creating Partially Initialized Objects
├── Using Objects Without Clear Responsibility
├── Creating God Objects
├── Mixing Unrelated Responsibilities
├── High Coupling Between Objects
├── Low Cohesion
├── Poor Object Relationships
├── Wrong Use of Aggregation
├── Wrong Use of Composition
├── Duplicating Shared Objects Unnecessarily
└── Sharing Mutable Objects Without Understanding Consequences

Best Practices

  • Understand the difference between a class and an object.
  • Remember that an object is an instance of a class.
  • Use meaningful reference variable names.
  • Create objects only when they represent meaningful entities or responsibilities.
  • Initialize objects into valid states.
  • Prefer constructor initialization for required state.
  • Use methods to protect important state changes.
  • Avoid exposing sensitive mutable fields publicly.
  • Use private fields when internal state should be protected.
  • Validate values before modifying object state.
  • Understand that reference variables do not contain complete objects.
  • Remember that multiple references can point to one object.
  • Be careful when sharing mutable objects.
  • Do not assume reference assignment creates a copy.
  • Create a new object when independent state is required.
  • Use deep copying when nested mutable state must be independent.
  • Use defensive copying to protect internal mutable state.
  • Check for null only when absence is a valid possibility.
  • Avoid unnecessary null values through good initialization.
  • Never access instance members through null.
  • Remember that Java is always pass-by-value.
  • Understand that object reference values are copied into method parameters.
  • Remember that methods can modify an object through a copied reference.
  • Remember that parameter reassignment does not reassign the caller variable.
  • Use == when checking whether references point to the same object.
  • Use equals when checking logical equality.
  • Override equals carefully.
  • Override hashCode consistently with equals.
  • Provide useful toString implementations for important domain objects.
  • Do not treat hash codes as guaranteed unique identifiers.
  • Understand the difference between object identity and object equality.
  • Use immutable objects when stable values are beneficial.
  • Use mutable objects when controlled state changes are part of the domain.
  • Keep object responsibilities focused.
  • Aim for high cohesion.
  • Aim for low coupling.
  • Design clear object relationships.
  • Use association for general interaction.
  • Use aggregation for independent has-a relationships.
  • Use composition for strong ownership.
  • Make object ownership clear.
  • Avoid unnecessary global shared mutable state.
  • Use static state only when data genuinely belongs to the class.
  • Remember that each object has independent instance state.
  • Remember that static state is shared.
  • Create individual objects for object array elements.
  • Check object array elements before use when they may be null.
  • Use enhanced for loops when indexes are unnecessary.
  • Use method chaining only when it improves readability.
  • Avoid excessively long fluent chains.
  • Use temporary objects only when later access is unnecessary.
  • Do not depend on immediate garbage collection.
  • Do not call System.gc() as normal application logic.
  • Do not rely on finalization.
  • Use try-with-resources for external resources.
  • Understand object reachability.
  • Allow the JVM to manage normal object memory.
  • Avoid premature optimization based on guessed object allocation costs.
  • Profile applications before memory optimization.
  • Test objects with valid data.
  • Test objects with invalid data.
  • Test object state changes.
  • Test shared references.
  • Test independent objects.
  • Test equality behavior.
  • Test null scenarios when relevant.
  • Test nested object relationships.
  • Document unusual ownership rules.
  • Prefer clear object models over clever structures.
  • Refactor objects that accumulate unrelated responsibilities.

Object Selection Guide

Object Decision Guide
NEED AN ACTUAL INSTANCE?

        │
        ├── NO ──────► USE CLASS-LEVEL DESIGN
        │
        └── YES
              │
              ▼

DOES EACH ENTITY NEED ITS OWN STATE?

        │
        ├── YES ─────► CREATE SEPARATE OBJECTS
        │
        └── NO
              │
              ▼

IS DATA SHARED BY THE CLASS?

        │
        ├── YES ─────► CONSIDER STATIC STATE
        │
        └── NO ──────► RECHECK DESIGN


NEED TO SHARE SAME OBJECT?

        │
        ├── YES ─────► COPY REFERENCE
        │
        └── NO
              │
              ▼

NEED INDEPENDENT OBJECT?

        │
        ├── YES ─────► CREATE COPY
        │
        └── NO ──────► SHARE REFERENCE


NESTED MUTABLE OBJECTS?

        │
        ├── NO ──────► SIMPLE COPY MAY WORK
        │
        └── YES
              │
              ▼

MUST NESTED STATE BE INDEPENDENT?

        │
        ├── YES ─────► DEEP COPY
        │
        └── NO ──────► SHALLOW COPY MAY WORK


CAN OBJECT BE ABSENT?

        │
        ├── YES ─────► HANDLE null INTENTIONALLY
        │
        └── NO ──────► REQUIRE VALID INITIALIZATION


SHOULD STATE CHANGE?

        │
        ├── YES ─────► CONTROLLED MUTABLE OBJECT
        │
        └── NO ──────► CONSIDER IMMUTABLE OBJECT

Object Checklist

Checklist
OBJECT CHECKLIST

[ ] Class and object are distinguished

[ ] Object represents a meaningful instance

[ ] Object has clear state

[ ] Object has clear behavior

[ ] Object identity is understood

[ ] Object is created with new when required

[ ] Reference variable name is meaningful

[ ] Reference and object are not confused

[ ] Object starts in a valid state

[ ] Required fields are initialized

[ ] Default field values are understood

[ ] Instance state is independent per object

[ ] Static state is intentionally shared

[ ] Fields are accessed safely

[ ] State changes are validated

[ ] Methods protect important behavior

[ ] null is used intentionally

[ ] null references are checked when necessary

[ ] Instance members are never accessed through null

[ ] Multiple references to one object are understood

[ ] Reference assignment is not mistaken for object copying

[ ] Reference reassignment behavior is understood

[ ] Java pass-by-value behavior is understood

[ ] Copied reference values are understood

[ ] Method object modifications are intentional

[ ] Parameter reassignment behavior is understood

[ ] Returned objects have clear ownership

[ ] Nested objects have clear relationships

[ ] Association is intentional

[ ] Aggregation is intentional

[ ] Composition is intentional

[ ] Object ownership is clear

[ ] == is used only for identity comparison when intended

[ ] equals is used for logical equality

[ ] equals contract is respected

[ ] hashCode is consistent with equals

[ ] toString provides useful output when needed

[ ] Hash codes are not treated as unique IDs

[ ] Reference copy and object copy are distinguished

[ ] Shallow copy behavior is understood

[ ] Deep copy is used when independence is required

[ ] Mutable nested objects are handled carefully

[ ] Defensive copying is used when needed

[ ] Mutability is intentional

[ ] Immutability is considered where useful

[ ] Object lifecycle is understood

[ ] Reachability is understood

[ ] Unreachable objects are left to garbage collection

[ ] System.gc() is not relied upon

[ ] finalize is not used

[ ] External resources are closed explicitly

[ ] Object arrays are initialized correctly

[ ] Individual array elements are created

[ ] null array elements are handled

[ ] Method chaining improves readability

[ ] Fluent methods return appropriate references

[ ] Temporary objects are used intentionally

[ ] Object relationships remain understandable

[ ] High cohesion is maintained

[ ] Low coupling is maintained

[ ] God objects are avoided

[ ] Shared mutable state is minimized

[ ] Object behavior is tested

[ ] Object state changes are tested

[ ] Equality behavior is tested

[ ] Shared reference behavior is tested

[ ] Independent copy behavior is tested

[ ] null scenarios are tested when relevant

Common Misconceptions

Avoid These Misconceptions
  • A class is not an object.
  • An object is an instance of a class.
  • One class can create many objects.
  • Each object has its own instance state.
  • Static state is shared at class level.
  • A reference variable is not the complete object.
  • The new keyword creates an object.
  • Declaring a reference variable does not always create an object.
  • A null reference does not point to an object.
  • null is not an object.
  • null cannot be assigned to primitive variables.
  • Accessing an instance member through null causes NullPointerException.
  • Reference assignment does not copy an object.
  • Two references can point to the same object.
  • Changing an object through one reference can be visible through another reference.
  • Reassigning one reference does not automatically change another reference.
  • Java is not pass-by-reference.
  • Java is always pass-by-value.
  • When passing an object, the reference value is copied.
  • A method can modify an object through a copied reference.
  • Reassigning a method parameter does not reassign the caller variable.
  • The == operator does not normally compare object content.
  • The == operator compares reference identity.
  • The equals method is used for logical equality.
  • The default equals implementation does not automatically compare every field.
  • Equal objects must have equal hash codes.
  • Hash codes are not guaranteed to be unique.
  • toString does not automatically provide business-friendly output.
  • Every Java class indirectly inherits from Object.
  • An object array initially stores null references.
  • Creating an object array does not create all element objects.
  • Copying a reference is not cloning an object.
  • A shallow copy can share nested mutable objects.
  • A deep copy creates independent nested state.
  • Mutable objects can change after creation.
  • Immutable objects do not expose state-changing behavior.
  • Setting a reference to null does not immediately delete the object.
  • An unreachable object is not necessarily collected immediately.
  • System.gc() does not guarantee immediate garbage collection.
  • Garbage collection does not replace resource management.
  • Files and database connections should be closed explicitly.
  • finalize should not be used for modern cleanup logic.
  • Objects can contain references to other objects.
  • Object relationships affect application design.
  • Composition is stronger than general association.
  • Not every object should be globally shared.
  • Not every object should be mutable.
  • Not every object should be immutable.
  • More objects do not automatically mean better design.
  • Good objects have clear responsibilities.
  • Object ownership should be intentional.
  • Object identity and logical equality are different concepts.

Practice Exercises

Exercise 1: Create Student Objects
  • Create a Student class.
  • Add name, age, and marks fields.
  • Create three different Student objects.
  • Assign different state to each object.
  • Display all object values.
Exercise 2: Independent Object State
  • Create two BankAccount objects.
  • Give each object a different balance.
  • Deposit money into the first account.
  • Withdraw money from the second account.
  • Verify that each object maintains independent state.
Exercise 3: Shared References
  • Create one Product object.
  • Create a second reference pointing to the same object.
  • Change the product price through the second reference.
  • Read the price through the first reference.
  • Explain the result.
Exercise 4: Object Method Arguments
  • Create an Employee object.
  • Pass it to a method.
  • Modify its salary inside the method.
  • Verify the changed salary outside the method.
  • Explain why the change is visible.
Exercise 5: Parameter Reassignment
  • Create a Student object.
  • Pass it to a method.
  • Create a new Student inside the method.
  • Assign the new object to the parameter.
  • Verify whether the original caller variable changed.
Exercise 6: Object Array
  • Create an array for five Product references.
  • Create five Product objects.
  • Store them in the array.
  • Display every product using a loop.
  • Calculate the total value of all products.
Exercise 7: Object Relationships
  • Create Address and Employee classes.
  • Store an Address reference inside Employee.
  • Create separate objects.
  • Connect the objects.
  • Display employee and address information.
Exercise 8: Reference Equality
  • Create two separate Student objects.
  • Give them identical values.
  • Compare them with ==.
  • Create another reference to the first object.
  • Compare those references with ==.
Exercise 9: Object Copying
  • Create a Student object with an Address object.
  • Create a reference copy.
  • Create a shallow copy.
  • Create a deep copy.
  • Modify the address and compare all results.
Exercise 10: Mini Order System
  • Create Customer, Product, and Order classes.
  • Create multiple customer and product objects.
  • Connect them through Order objects.
  • Calculate order totals.
  • Display a complete order summary.

Common Interview Questions

What is an object in Java?

An object is a runtime instance of a class that has state, behavior, and identity.

What is the difference between a class and an object?

A class is a blueprint or type definition, while an object is an actual runtime instance of that class.

What are the main characteristics of an object?

The three main characteristics are state, behavior, and identity.

What does the new keyword do?

It creates a new object, initializes it, invokes the appropriate constructor, and returns a reference.

What is a reference variable?

A reference variable stores a reference to an object rather than the complete object itself.

Can multiple references point to the same object?

Yes. Multiple reference variables can refer to the same object.

Does assigning one object variable to another copy the object?

No. It copies the reference value, so both variables can point to the same object.

What is null?

null represents the absence of an object reference.

What causes NullPointerException?

It commonly occurs when code tries to access an instance member through a null reference.

Is Java pass-by-reference?

No. Java is always pass-by-value. For objects, the reference value is copied.

Can a method modify an object passed as an argument?

Yes. The copied reference can point to the same object, allowing the method to modify that object.

Does reassigning an object parameter change the caller variable?

No. Reassignment changes only the local copy of the reference.

What does == compare for objects?

It compares whether two references point to the same object.

What does equals compare?

It can compare logical equality as defined by the class implementation.

Why should hashCode be overridden with equals?

Equal objects must produce the same hash code to work correctly with hash-based collections.

What is a shallow copy?

A shallow copy creates a new outer object but shares references to nested mutable objects.

What is a deep copy?

A deep copy creates independent copies of the outer object and relevant nested mutable objects.

What is garbage collection?

Garbage collection is the JVM process that may reclaim memory occupied by unreachable objects.

Does System.gc() guarantee garbage collection?

No. It only requests that the JVM consider running garbage collection.

What is an object array?

An object array is an array whose elements store references to objects.

Does new Student[5] create five Student objects?

No. It creates an array containing five null reference elements.

Frequently Asked Questions

Can an object exist without a class?

Normal Java objects are instances of classes or array types and have runtime type information.

Can a class create unlimited objects?

A class can be used to create many objects, limited by available resources and application constraints.

Does every object have separate fields?

Each object has its own instance fields, while static fields are shared at class level.

Where are objects stored?

Objects are generally allocated in heap memory, although JVM implementations may apply optimizations.

Is a reference the memory address?

A Java reference should be treated as an abstract reference to an object rather than as a directly usable raw memory address.

Can a reference change which object it points to?

Yes, unless the reference variable itself is final.

Can one object contain another object?

An object can contain a reference to another object.

Can objects be passed to methods?

Yes. Java copies the object reference value into the method parameter.

Can methods return objects?

Yes. A method can return an object reference.

What should I learn after Objects?

The next lesson covers Constructors in Java.

Key Takeaways

  • An object is a runtime instance of a class.
  • A class is a blueprint.
  • An object is an actual entity created from the blueprint.
  • Objects have state.
  • Objects have behavior.
  • Objects have identity.
  • State is represented by field values.
  • Behavior is represented by methods.
  • Identity distinguishes one object from another.
  • The new keyword creates objects.
  • Object creation allocates and initializes object state.
  • A constructor runs during object creation.
  • A reference variable refers to an object.
  • A reference is not the complete object.
  • Objects are generally allocated on the heap.
  • Local references are associated with method execution.
  • The dot operator accesses object members.
  • Fields can be read and updated through references.
  • Methods can be called through references.
  • One class can create many objects.
  • Each object has independent instance state.
  • Static state is shared at class level.
  • Fields receive default values.
  • Objects should be initialized into valid states.
  • Objects can be initialized through fields, methods, blocks, and constructors.
  • Reference assignment copies a reference value.
  • Reference assignment does not copy an object.
  • Multiple references can point to one object.
  • Changes through one reference can be visible through another reference.
  • References can be reassigned.
  • null represents the absence of an object reference.
  • Accessing instance members through null causes NullPointerException.
  • Null checks should be used when absence is valid.
  • Anonymous objects have no stored named reference.
  • Objects can be passed to methods.
  • Java is always pass-by-value.
  • Object reference values are copied into method parameters.
  • A copied reference can point to the same object.
  • Methods can modify objects through copied references.
  • Reassigning a parameter does not reassign the caller variable.
  • Methods can return object references.
  • Objects can contain references to other objects.
  • Object graphs represent connected objects.
  • Association represents general interaction.
  • Aggregation represents an independent has-a relationship.
  • Composition represents strong ownership.
  • Object identity is different from logical equality.
  • The == operator compares reference identity.
  • The equals method can define logical equality.
  • The hashCode method supports hash-based collections.
  • Equal objects must have equal hash codes.
  • The toString method represents an object as text.
  • The getClass method provides runtime type information.
  • Every Java class indirectly inherits from Object.
  • Reference copying is different from object copying.
  • Manual copying can create a separate object.
  • Shallow copies may share nested objects.
  • Deep copies create independent nested state.
  • Mutable objects can change state.
  • Immutable objects do not allow observable state changes after creation.
  • Objects have a lifecycle.
  • Reachable objects remain accessible.
  • Unreachable objects may become eligible for garbage collection.
  • Garbage collection is controlled by the JVM.
  • System.gc() does not guarantee immediate collection.
  • Garbage collection does not replace resource cleanup.
  • finalize should not be relied upon.
  • Object arrays store references.
  • New object arrays initially contain null elements.
  • Array elements require separate object creation.
  • String values are objects.
  • Wrapper classes represent primitive-like values as objects.
  • Method chaining uses returned object references.
  • Fluent APIs can improve readability.
  • Temporary objects are useful for immediate operations.
  • Object ownership should be clear.
  • Defensive copying protects mutable internal state.
  • Real applications are built from collaborating objects.
  • Good objects have clear responsibilities.
  • Good object models use clear relationships.
  • Good object design controls mutability.
  • Good object design protects valid state.
  • Good object design minimizes unnecessary shared mutable state.
  • Understanding objects is essential for constructors, encapsulation, inheritance, polymorphism, interfaces, collections, Spring, and enterprise Java development.

Summary

Objects are the actual runtime entities created from classes. While a class defines structure and behavior, an object contains real state, has its own identity, and can perform the behavior defined by its class.

Objects are normally created using the new keyword and accessed through reference variables. The reference and the object are different: a reference identifies an object, while the object contains its actual instance state.

Multiple objects created from the same class have independent instance state. Multiple references can also point to the same object, which means modifications through one reference can be observed through another.

Java is always pass-by-value. When objects are passed to methods, Java copies the reference value. This allows methods to modify the referenced object but does not allow parameter reassignment to replace the caller variable.

Object identity is different from logical equality. The == operator checks whether references point to the same object, while equals can be used to define meaningful content-based equality.

Objects can form relationships through association, aggregation, and composition. They can also be mutable or immutable, copied by reference or by state, stored in arrays, passed between methods, and connected into complex object graphs.

When objects are no longer reachable, they may become eligible for garbage collection. The JVM manages normal object memory automatically, but external resources such as files and database connections still require explicit resource management.

Mastering objects is essential because Java applications are built from objects that collaborate with each other. Constructors, encapsulation, inheritance, polymorphism, abstraction, interfaces, collections, Spring components, and enterprise systems all depend on a strong understanding of object behavior.

Lesson 18 Completed
  • You understand what an object is.
  • You understand why objects are needed.
  • You can distinguish a class from an object.
  • You understand object state.
  • You understand object behavior.
  • You understand object identity.
  • You can create objects.
  • You understand the new keyword.
  • You understand the object creation process.
  • You understand reference variables.
  • You understand the basic object memory model.
  • You understand stack and heap concepts.
  • You can access object fields.
  • You can update object fields.
  • You can call object methods.
  • You can create multiple objects.
  • You understand independent object state.
  • You understand shared static state.
  • You understand default object state.
  • You understand object initialization.
  • You understand field initialization.
  • You understand method-based initialization.
  • You understand constructor initialization.
  • You understand object references.
  • You understand reference assignment.
  • You understand multiple references.
  • You understand reference reassignment.
  • You understand null references.
  • You understand NullPointerException.
  • You can check references for null.
  • You understand anonymous objects.
  • You can pass objects to methods.
  • You understand that Java is pass-by-value.
  • You understand copied reference values.
  • You understand object modification through methods.
  • You understand parameter reassignment.
  • You can return objects from methods.
  • You understand objects inside objects.
  • You understand object relationships.
  • You understand association.
  • You understand aggregation.
  • You understand composition.
  • You understand object identity.
  • You understand reference equality.
  • You understand logical equality.
  • You understand the equals method.
  • You understand the hashCode method.
  • You understand the toString method.
  • You understand the getClass method.
  • You understand the Object class.
  • You understand object copying.
  • You understand reference copying.
  • You understand manual object copying.
  • You understand shallow copying.
  • You understand deep copying.
  • You understand mutable objects.
  • You understand immutable objects.
  • You understand the object lifecycle.
  • You understand reachable objects.
  • You understand unreachable objects.
  • You understand garbage collection.
  • You understand garbage collection eligibility.
  • You understand System.gc().
  • You understand why finalization should not be used.
  • You understand object arrays.
  • You understand arrays of references.
  • You can create objects inside arrays.
  • You can iterate through object arrays.
  • You understand that Strings are objects.
  • You understand wrapper objects.
  • You understand method chaining.
  • You understand fluent objects.
  • You understand temporary objects.
  • You understand object ownership.
  • You understand defensive copying.
  • You can create real-world Student objects.
  • You can create BankAccount objects.
  • You can create Product objects.
  • You can create Employee objects.
  • You can create connected Order objects.
  • You understand the object design process.
  • You can identify common object errors.
  • You know object best practices.
  • You are ready to learn Constructors.
Next Lesson →

Constructors in Java