Java – what happens to the returned object when I call “new object()” without storing the return?

Suppose we have some code as follows (I know this is a bad practice):

try {

new myObject();

} catch {

//stuff

}

What happens to the returned object? Is it still stored on the heap? Will this throw a compile time error?

Solution

It is created and immediately eligible for garbage collection

I don't see any reason why it should throw an exception (unless, of course, the MyObject constructor throws one), it's perfectly legal syntax

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>