`new` Operator in Java

java dev.to

The new operator is one of the first Java keywords every developer learns. Every time you create an object, you're using new.

But what actually happens behind the scenes?

Where is the object created? Why doesn't Java have a delete operator like C++? What's the difference between new and reflection-based object creation?

In this article, we'll answer all of these questions with simple explanations and practical examples.


What is the new Operator?

The new operator is used to create objects in Java.

Every object in Java is created using new (except for a few special cases like string literals and certain JVM optimizations).


Two Important Facts

  • The new operator creates an object.
  • Java does not have a delete operator. Unused objects are automatically removed by the Garbage Collector (GC).

Syntax

ClassName reference = new ClassName();
Enter fullscreen mode Exit fullscreen mode

Examples

Creating a String

String name = new String("Rajesh");
Enter fullscreen mode Exit fullscreen mode

Creating a Thread

Thread thread = new Thread();
Enter fullscreen mode Exit fullscreen mode

Creating Your Own Class

Test obj = new Test();
Enter fullscreen mode Exit fullscreen mode

What Happens When You Use new?

When Java executes

Test obj = new Test();
Enter fullscreen mode Exit fullscreen mode

three things happen:

  1. Memory is allocated on the Heap.
  2. The constructor is invoked to initialize the object.
  3. A reference to the newly created object is returned.
Test obj = new Test();
//         ↑
//     Object created on Heap

//                  ↑
//          Constructor executed

//  Reference returned and stored in obj
Enter fullscreen mode Exit fullscreen mode

Where Are Objects Created?

Objects created using new are stored in the Heap Memory.

The reference variable itself is usually stored in the current method's stack frame (for local variables), while the object lives on the heap.

Stack Memory                Heap Memory

obj  ───────────────►   Test Object
Enter fullscreen mode Exit fullscreen mode

Why Doesn't Java Have a delete Operator?

Unlike C++, Java automatically manages memory.

In C++:

  • Programmer creates objects using new.
  • Programmer must manually destroy them using delete.

If the programmer forgets to call delete, memory leaks occur.


Java vs C++

Feature Java C++
Create object new new
Destroy object Garbage Collector delete
Memory management Automatic Manual

Java's automatic memory management reduces:

  • Memory leaks
  • Dangling pointers
  • Double deletion errors
  • Many application crashes

What is Garbage Collection?

The Garbage Collector (GC) automatically removes objects that are no longer being used.

Programmers create objects.

The JVM decides when unused objects should be destroyed.


When Is an Object Eligible for Garbage Collection?

An object becomes eligible for garbage collection when no live references point to it.

Eligible does not mean it is immediately removed. The JVM decides when to run the Garbage Collector.


Method 1: Assign null

String name = new String("Rajesh");

name = null;
Enter fullscreen mode Exit fullscreen mode

The object has no references now and becomes eligible for GC.


Method 2: Reassign the Reference

String name = new String("Rajesh");

name = new String("Bhola");
Enter fullscreen mode Exit fullscreen mode

Now:

  • The first String object has no references.
  • It becomes eligible for GC.
  • The second object is referenced by name.

Method 3: Local Objects Going Out of Scope

public void display() {

    Test obj = new Test();

}
Enter fullscreen mode Exit fullscreen mode

When the method finishes,

obj goes out of scope.

If no other reference exists, the object becomes eligible for GC.


new vs Reflection-Based Object Creation

There are two common ways to create objects.

1. Using new

Test obj = new Test();
Enter fullscreen mode Exit fullscreen mode

The class name is known during compilation.


2. Using Reflection

Sometimes the class name isn't known until runtime.

Example:

Object obj =
        Class.forName("com.example.Test")
             .getDeclaredConstructor()
             .newInstance();
Enter fullscreen mode Exit fullscreen mode

Here, Java creates the object dynamically.

This technique is heavily used by frameworks.


Why Was Class.newInstance() Deprecated?

Older Java versions used:

Class.forName("Test").newInstance();
Enter fullscreen mode Exit fullscreen mode

This method has been deprecated since Java 9 because it has poor exception handling.

Modern Java recommends:

Object obj =
        Class.forName("Test")
             .getDeclaredConstructor()
             .newInstance();
Enter fullscreen mode Exit fullscreen mode

This approach provides clearer and safer exception handling.

For modern Java development, always prefer Constructor::newInstance() over Class::newInstance().


Dynamic Object Creation Example

public class Test {

    public static void main(String[] args) throws Exception {

        Object obj =
                Class.forName(args[0])
                     .getDeclaredConstructor()
                     .newInstance();

        System.out.println(obj.getClass().getName());
    }
}
Enter fullscreen mode Exit fullscreen mode

Run:

java Test java.lang.String
Enter fullscreen mode Exit fullscreen mode

Output

java.lang.String
Enter fullscreen mode Exit fullscreen mode

Run:

java Test java.lang.Thread
Enter fullscreen mode Exit fullscreen mode

Output

java.lang.Thread
Enter fullscreen mode Exit fullscreen mode

The class is chosen at runtime.


new vs Reflection

Feature new Reflection (newInstance)
Type Operator Method
Class name known Compile time Runtime
Constructor called Any accessible constructor Constructor obtained via reflection
Used in Normal programming Frameworks, plugins, dependency injection

Common Exceptions

Using new

Test obj = new Test();
Enter fullscreen mode Exit fullscreen mode

If the class was present during compilation but missing at runtime, Java throws:

NoClassDefFoundError
Enter fullscreen mode Exit fullscreen mode

This is an unchecked error.


Using Reflection

Class.forName("Test");
Enter fullscreen mode Exit fullscreen mode

If the class cannot be found, Java throws:

ClassNotFoundException
Enter fullscreen mode Exit fullscreen mode

This is a checked exception.


ClassNotFoundException vs NoClassDefFoundError

Feature ClassNotFoundException NoClassDefFoundError
Type Checked Exception Unchecked Error
Occurs with Class.forName() new
Reason Class not found during dynamic loading Class available at compile time but missing at runtime

Where Is Reflection Used?

Reflection-based object creation is widely used in:

  • Spring Framework
  • Hibernate
  • Dependency Injection
  • Plugin architectures
  • JDBC Driver Loading
  • Serialization libraries

Example:

Class.forName("com.mysql.cj.jdbc.Driver");
Enter fullscreen mode Exit fullscreen mode

Although modern JDBC drivers are auto-loaded, this statement is still a popular interview topic.


Summary Table

Feature new Operator
Purpose Creates objects
Memory location Heap
Calls constructor ✅ Yes
Returns Object reference
Object destruction Garbage Collector
delete operator available? ❌ No

Interview Questions

What does the new operator do?

It allocates memory on the heap, invokes the constructor, and returns an object reference.


Where are objects created?

On the Heap.


Does Java have a delete operator?

No.

Object destruction is handled automatically by the Garbage Collector.


When is an object eligible for Garbage Collection?

When no live references point to it.


What is the difference between new and reflection?

  • new is used when the class is known at compile time.
  • Reflection is used when the class is determined at runtime.

Why is Class.newInstance() deprecated?

Because it doesn't handle constructor exceptions properly.

Use:

getDeclaredConstructor().newInstance()
Enter fullscreen mode Exit fullscreen mode

instead.


Memory Tricks 🧠

new

You know the class today.

Test obj = new Test();
Enter fullscreen mode Exit fullscreen mode

Reflection

You'll decide the class later.

Class.forName(className)
Enter fullscreen mode Exit fullscreen mode

Garbage Collection

No references = Eligible for GC

(Remember: eligible doesn't mean immediately collected.)


Easy Way to Remember

new creates. GC destroys.

You create objects.

The JVM cleans them up automatically when they're no longer reachable.


Key Takeaways

  • The new operator creates objects by allocating memory on the heap, invoking the constructor, and returning a reference.
  • Java has no delete operator because the Garbage Collector automatically reclaims memory occupied by unreachable objects.
  • An object becomes eligible for garbage collection when no live references point to it, although the JVM decides when collection actually occurs.
  • Reflection allows objects to be created dynamically when the class name is known only at runtime.
  • Class.newInstance() is deprecated; modern Java uses getDeclaredConstructor().newInstance() for reflective object creation.
  • Understanding object creation, heap memory, garbage collection, and reflection is essential for writing efficient Java applications and succeeding in interviews.

Happy Coding!

Source: dev.to

arrow_back Back to Tutorials