Delete an Object in Java

Rupam Yadav Jan 25, 2021 Dec 13, 2020
  1. Java Delete an Object by Referencing It to null
  2. Java Delete an Object Confined in a Scope by Referencing It to null
Delete an Object in Java

We will learn how to delete an object in Java and use a garbage collector in the following examples.

Java Delete an Object by Referencing It to null

In the first example of deleting a Java object, we create a class with a constructor that initializes the variables name and age. In the main method, an object of the User class is created, and values for name and age are passed. Now that the object has been initialized, we can use it to get age and compare it to display a message. But after that, we want to delete myObject so that it cannot be used further.

To do this, we initialize myObject once again but with null. Once the myObject is null, we cannot use it to call any of its methods or variables, and it will throw an exception if we do so. System.gc() is used to collect any leftover garbage so that there are no empty fields or objects left to free the memory.

We can see that there is a finalize() method in the User class. It is an overridden method that is called on the object before collecting the garbage.

public class JavaDeleteObject {
    public static void main(String[] args) {

        User myObject = new User("John", 30);
        int userAge = myObject.age;
      
        if (userAge > 25) {
            System.out.println("User age is : " + userAge);
        } else {
            System.out.println("User age is less than 25 : " + userAge);
        }
        myObject = null;
        System.gc();
      
        System.out.println(myObject.age);

    }

}

class User {
    String name;
    int age;

    User(String n, int a) {
        name = n;
        age = a;
    }

    protected void finalize() {
        System.out.println("Object is garbage collected.");
    }
}

Output:

User age is : 30
Object is garbage collected.
Exception in thread "main" java.lang.NullPointerException
	at com.company.JavaDeleteObject.main(JavaDeleteObject.java:18)

Java Delete an Object Confined in a Scope by Referencing It to null

In the code shown below, we have a Student class with three data members that are assigned values using the class’s parameterized constructor. It has a showDetails() method and showNextIndex() method. It also has the finalize() method to display the index of the next student.

New objects of the Student class is created using the new keyword. The Student class methods are called on the student1 and student2 objects. Later in the code, we have created more Student class objects inside a scope. After using them, we call System.gc(), which requests the JVM to garbage collect the two objects created in this scope.

The nextIndex value is incremented to 3 before entering the scope, and before leaving the scope it is 5. To decrement the nextIndex value the finalize() method is called using System.runFinalization() twice for the value 5 before the objects are garbage collected.

The correct nextIndex value is then shown, excluding the values which were inside the scope.

class Student {
  
    private int index;
    private String name;
    private int age;
    private static int nextIndex=1;
  
    Student(String name,int age){
        this.name = name;
        this.age = age;
        this.index = nextIndex++;
    }
  
    public void showDetails(){
        System.out.println("Student at Index : "+index+", Student name: "+name +", age: "+age);
    }
  
    public void showNextIndex(){
        System.out.println("Next Index: "+nextIndex);
    }
  
    protected void finalize()
    {
        --nextIndex;
    }
}

class UseStudent{
    public static void main(String[] args){
        Student student1 = new Student("John",23);
        Student student2 = new Student("Doe",20);
        student1.showDetails();
        student2.showDetails();
        student1.showNextIndex();
        student2.showNextIndex();
        {
            Student student3 = new Student("Sam",22);
            Student student4 = new Student("Ben",21);
            student3.showDetails();
            student4.showDetails();
            student3.showNextIndex();
            student4.showNextIndex();
          
            student3 = student4 = null;
            System.gc();
            System.runFinalization();
        }
        student2.showNextIndex();
    }
}

Output:

Student at Index : 1, Student name: John, age: 23
Student at Index : 2, Student name: Doe, age: 20
Next Index: 3
Next Index: 3
Student at Index : 3, Student name: Sam, age: 22
Student at Index : 4, Student name: Ben, age: 21
Next Index: 5
Next Index: 5
Next Index: 3
Author: Rupam Yadav
Rupam Yadav avatar Rupam Yadav avatar

Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.

LinkedIn

Related Article - Java Object