Rohan Agarwal Rohan Agarwal - 4 months ago 15
Java Question

Java memory questions about 'new' keyword

What happens if you run the following code..

while (true) {
String x = new String("ABC");
}


in terms of memory?

Is String x allocated on the stack or on the heap? Will the program eventually crash because of a memory overflow, or will garbage collection prevent that? Does the new keyword always create the object on the heap? When is an object created on the stack?

Thanks!

EJP EJP
Answer

Is String x allocated on the stack or on the heap?

x isn't a String. It is a reference to a String. The reference is a local variable, and so goes on the stack. The String is an object, and so goes on the heap.

Will the program eventually crash because of a memory overflow

Probably not.

or will garbage collection prevent that?

It should.

Does the new keyword always create the object on the heap?

Yes.

When is an object created on the stack?

Never ... unless the JVM decides it cannot escape the current scope and so decides to do so.