问题描述
如果运行以下代码会发生什么.
What happens if you run the following code..
while (true) {
String x = new String("ABC");
}
在记忆方面?
字符串x是分配在堆栈上还是堆上?程序最终会由于内存溢出而崩溃,还是通过垃圾回收来防止这种情况发生? new关键字是否总是在堆上创建对象?什么时候在堆栈上创建对象?
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?
谢谢!
推荐答案
x
不是String
.它是对String
的引用.该引用是一个局部变量,因此在堆栈上进行. String
是一个对象,因此继续在堆上.
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.
可能不是.
应该.
是的
从不...除非JVM决定无法逃避当前作用域,所以决定这样做.
Never ... unless the JVM decides it cannot escape the current scope and so decides to do so.
这篇关于Java内存有关"new"关键字的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!