关于 'new'关键字的Java内存问题

标签 java memory heap-memory stack-memory

如果你运行以下代码会发生什么..

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/

相关文章:

java - 我无法在 android 5.1 上获取通知图像,始终返回 null

c++ - C++中的对象大小是不可预测的

android - 相同的应用程序在不同的 Android 设备上使用不同数量的内存

java - 表单内的 Thymeleaf href 转到不同页面

java - 在 Firebase 数据库 Android Java 中写入新的整数数据

java - 如何在Java中读取.EXE文件的内容

c - 如何使用 malloc() 在 redhat 中分配比 RAM 多的内存?

java - Eclipse 内存不足且运行缓慢

c++ - 谷歌模拟全局模拟对象内存泄漏

java - 分页对垃圾回收有什么影响?