如果你运行以下代码会发生什么..
while (true) {
String x = new String("ABC");
}
在内存方面?
String x 是分配在栈上还是堆上?程序最终会因为内存溢出而崩溃,还是垃圾收集会阻止这种情况? new 关键字是否总是在堆上创建对象?什么时候在堆栈上创建对象?
谢谢!
最佳答案
Is String x allocated on the stack or on the heap?
x
不是 String
。它是对 String
的引用。引用是一个局部变量,所以在堆栈上。 String
是一个对象,所以在堆上。
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?
永远不要......除非 JVM 决定它不能逃离当前范围并决定这样做。
关于关于 'new'关键字的Java内存问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15063440/