Objects and Object Lifecycle in Java

Master object declaration, instantiation, nested classes, object lifecycle, creation, reassigning references, and garbage collection for the OCP 21 exam.

Table of Contents

1. Object Fundamentals

In Java, objects are instances of classes. They contain state (fields) and behavior (methods). Objects are created on the heap and accessed through references.

1.1 What is an Object?

An object is a runtime entity that represents an instance of a class. It has:

  • State: Represented by fields (instance variables)
  • Behavior: Represented by methods
  • Identity: Unique reference in memory
Example:
// Class definition class Person {
    String name;
    // State (field) int age;
    // State (field) void speak() {
        // Behavior (method) System.out.println("Hello, I'm" + name);
    }
} // Creating an object Person person = new Person();
// Object created on heap person.name ="Alice";
// Setting state person.age = 30;
// Setting state person.speak();
// Calling
behavior

2. Object Declaration

Object declaration creates a reference variable that can hold a reference to an object.

2.1 Declaration Syntax

Example:
// Declaration without initialization Person person;
// Reference variable, no object created yet // person is null at this point // Declaration with initialization Person person2 = new Person();
// Object created and assigned // Multiple declarations Person p1, p2, p3;
// All are null references // Declaration with type inference (Java 10+) var person3 = new Person();
// Type inferred as
Person

2.2 Null References

Example:
Person person = null;
// Explicit null assignment // Checking for null if (person == null) {
    System.out.println("No object referenced");
} // NullPointerException if accessing null reference // person.name ="Alice";
// Would throw NullPointerException // Safe access if (person != null) {
    person.name ="Alice";
}

3. Object Instantiation

Object instantiation creates an actual object in memory using the new keyword.

3.1 Using the new Keyword

Example:
// Basic instantiation Person person = new Person();
// Instantiation with constructor arguments class Person {
    String name;
    int age;
    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
} Person alice = new Person("Alice", 30);
Person bob = new Person("Bob", 25);
// Anonymous object (no reference stored) new Person("Charlie", 35).speak();
// Object used
immediately

3.2 Object Creation Process

When new is called, the following steps occur:

  1. Memory is allocated on the heap
  2. Fields are initialized to default values
  3. Instance initializers are executed
  4. Constructor is called
  5. Reference is returned
Example:
class Example {
    int value;
    // Default: 0 // Instance initializer {
        System.out.println("Instance initializer");
        value = 10;
    } // Constructor Example() {
    System.out.println("Constructor");
    value = 20;
}
} // Output when creating object: // Instance initializer // Constructor Example obj = new Example();
// value is
20

4. Object Lifecycle

An object goes through several stages during its lifetime.

4.1 Lifecycle Stages

  1. Creation: Object is instantiated with new
  2. Usage: Object is used through references
  3. Unreachable: No references point to the object
  4. Eligible for GC: Garbage collector can reclaim memory
  5. Finalization: finalize() method called (deprecated)
  6. Collection: Memory is reclaimed
Example:
// Stage 1: Creation Person person = new Person("Alice", 30);
// Stage 2: Usage person.speak();
person.age = 31;
// Stage 3: Reassignment (old object becomes unreachable) person = new Person("Bob", 25);
// Previous object eligible for GC // Stage 4: Explicit null assignment person = null;
// Object definitely eligible for
GC

4.2 Object State Changes

Example:
class Counter {
    private int count = 0;
    void increment() {
        count++;
    }
int getCount() {
    return count;
}
} Counter counter = new Counter();
// count = 0 counter.increment();
// count = 1 counter.increment();
// count = 2 System.out.println(counter.getCount());
// 2

5. References and Reassignment

Variables hold references to objects, not the objects themselves. Multiple references can point to the same object.

5.1 Reference Assignment

Example:
Person person1 = new Person("Alice", 30);
Person person2 = person1;
// Both reference same object person2.name ="Bob";
// Modifies the same object System.out.println(person1.name);
//"Bob" (same object!) // Reassignment person1 = new Person("Charlie", 25);
// person1 points to new object // person2 still points to original object (Alice/Bob) person2 = null;
// Removes reference, object still exists if person1 references
it

5.2 Reference Comparison

Example:
Person p1 = new Person("Alice", 30);
Person p2 = new Person("Alice", 30);
Person p3 = p1;
// Reference comparison (==) System.out.println(p1 == p2);
// false (different objects) System.out.println(p1 == p3);
// true (same object) // Content comparison (equals) System.out.println(p1.equals(p2));
// true (if equals() is overridden) // Null comparison Person p4 = null;
System.out.println(p1 == null);
// false System.out.println(p4 == null);
// true
Important: Reassigning a reference doesn't destroy the object. The object becomes eligible for garbage collection only when no references point to it.

6. Nested Classes

Java allows classes to be defined inside other classes. These are called nested classes.

6.1 Types of Nested Classes

  • Static Nested Class: Defined with static keyword
  • Inner Class: Non-static nested class
  • Local Class: Defined inside a method
  • Anonymous Class: Class without a name

6.2 Static Nested Class

Example:
class Outer {
    static class StaticNested {
        void display() {
            System.out.println("Static nested class");
        }
} } // Instantiation doesn't require outer class instance Outer.StaticNested nested = new Outer.StaticNested();

    nested.display();

6.3 Inner Class

Example:
class Outer {
    private String outerField ="Outer";
    class Inner {
        void display() {
            System.out.println("Inner class accessing:" + outerField);
        }
} } // Requires outer class instance Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
inner.display();

6.4 Local Class

Example:
class Outer {
    void method() {
        class Local {
            void display() {
                System.out.println("Local class");
            }
    } Local local = new Local();
local.display();
}
}

6.5 Anonymous Class

Example:
interface Greeting {
    void greet();
} // Anonymous class implementing interface Greeting greeting = new Greeting() {
@Override public void greet() {
    System.out.println("Hello from anonymous class");
}
};
greeting.greet();
// Anonymous class extending class class Animal {
    void makeSound() {
        System.out.println("Some sound");
    }
} Animal dog = new Animal() {
@Override void makeSound() {
    System.out.println("Woof!");
}
};
dog.makeSound();

7. Garbage Collection

Java automatically manages memory through garbage collection. Objects become eligible for garbage collection when they are no longer reachable.

7.1 When Objects Become Eligible

An object becomes eligible for garbage collection when:

  • No references point to it
  • All references are set to null
  • References go out of scope
  • Island of isolation (circular references with no external references)
Example:
// Method creates object void createObject() {
    Person person = new Person("Alice", 30);
    // Object eligible for GC when method ends } // Reassignment Person person = new Person("Alice", 30);
person = new Person("Bob", 25);
// First object eligible for GC // Null assignment Person person = new Person("Alice", 30);
person = null;
// Object eligible for GC // Island of isolation class Node {
    Node next;
}
Node n1 = new Node();
Node n2 = new Node();
n1.next = n2;
n2.next = n1;
n1 = null;
n2 = null;
// Both objects eligible for GC (circular
reference)

7.2 Requesting Garbage Collection

Note: You can suggest garbage collection with System.gc() , but the JVM decides when to actually run GC. This is rarely needed.
Example:
// Suggesting garbage collection (not guaranteed) System.gc();
// Runtime.getRuntime().gc() is equivalent
Runtime.getRuntime().gc();

7.3 Finalization (Deprecated)

Warning: The finalize() method is deprecated as of Java 9. Use try-with-resources or Cleaner API instead.
Example (Deprecated):
class Resource {
    @Deprecated @Override protected void finalize() throws Throwable {
        // Cleanup code (deprecated - don't use) super.finalize();

    }
}

8. Exam Key Points

Critical Concepts for OCP 21 Exam:

  • Object Declaration: Creates a reference variable, doesn't create object
  • Object Instantiation: new keyword creates object on heap
  • References: Variables hold references, not objects themselves
  • Multiple References: Multiple variables can reference same object
  • Reassignment: Changing reference doesn't destroy object
  • Null: Reference can be null, accessing null throws NullPointerException
  • Object Creation Order: Memory allocation → default values → initializers → constructor
  • Static Nested Class: Doesn't require outer class instance
  • Inner Class: Requires outer class instance, can access outer fields
  • Local Class: Defined inside method, has access to local variables (effectively final)
  • Anonymous Class: Class without name, used for one-time implementations
  • Garbage Collection: Automatic memory management, objects eligible when unreachable
  • Eligibility for GC: No references, null assignment, out of scope, island of isolation
  • System.gc(): Suggests GC but doesn't guarantee it
  • finalize(): Deprecated, don't rely on it
  • Reference Comparison: == compares references, equals() compares content
  • Object Identity: Each object has unique identity in memory

Post a Comment

0 Comments