Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 946
Rohan Agarwal Avatar asked Feb 25 '13 09:02

Rohan Agarwal


1 Answers

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.

like image 92
user207421 Avatar answered Oct 22 '22 21:10

user207421