Houssam Badri
Houssam Badri

Reputation: 2509

Best way to create objects in Java, and when do we have memory leak

Class A {
A();
}

First way:

A a = null;

Second way:

A a = new A();

What is the difference between these two object declarations? Is there any eventual Memory Leak problem?

Upvotes: 0

Views: 96

Answers (2)

Suresh Atta
Suresh Atta

Reputation: 121998

What is the difference between these two object declarations?

They are not the same as you are trying to compare the both.

First case is you are not creating any Object of A, just initializing it to null.

Later you are creating an Object for A with new. Coming to the memory aspect there no such leak here.

Garbage collector do the stuff when you are no references to your Object.

//code
A a = null;
//codes 
a.something() // NullpointerException

case 2

    //code
    A a = null;
    //codes 
   a = new A();
    a.something() // No NullpointerException

Upvotes: 3

Szymon
Szymon

Reputation: 43023

The first method (A a = null;) doesn't create an instance of the A class so the variable's value is null.

The second method (A a = new A();) creates an instance of the A class at the same time as declaring the variable.

Memory leaks are not caused just by instantiating variables as you need to instantiate variables anyway to use them. This is a more complicated topic.

Upvotes: 3

Related Questions