Java原语是在堆栈还是堆上? [英] Do Java primitives go on the Stack or the Heap?

查看:163
本文介绍了Java原语是在堆栈还是堆上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只知道非基元(对象)进入堆,方法进入堆栈,但原始变量怎么样?

I just know that the non-primitives (the objects) go on the heap, and methods go on the stack, but what about the primitive variables?

- 更新

根据答案,我可以说堆可以为给定对象创建一个新堆栈和堆?鉴于该对象将具有原始和引用变量..?

Based on the answers, I could say the heap can have a new stack and heap for a given object? Given that the object will have primitive and reference variables..?

推荐答案

本地定义的基元将在堆栈上。但是,如果将基元定义为对象实例的一部分,则该基元将位于堆上。

Primitives defined locally would be on the stack. However if a primitive were defined as part of an instance of an object, that primitive would be on the heap.

public class Test {
    private static class HeapClass {
        public int y; // When an instance of HeapClass is allocated, this will be on the heap.
    }
    public static void main(String[] args) {
        int x=1; // This is on the stack.
    }
}

关于更新:

对象没有自己的堆栈。在我的示例中, int y 实际上是 HeapClass 的每个实例的一部分。每当分配一个HeapClass实例时(例如 new Test.HeapClass()),HeapClass的所有成员变量都会被添加到堆中。因此,由于 HeapClass 的实例正在堆上分配, int y 将作为一部分在堆上。 HeapClass 的实例。

Objects do not have their own stack. In my example, int y would actually be part of each instance of HeapClass. Whenever an instance of HeapClass is allocated (e.g. new Test.HeapClass()), all member variables of HeapClass are added to the heap. Thus, since instances of HeapClass are being allocated on the heap, int y would be on the heap as part of an instance of HeapClass.

但是,在任何方法的主体中声明的所有原始变量都是 在堆栈上

However, all primitive variables declared in the body of any method would be on the stack.

如上例所示, int x 在堆栈上,因为它在方法体中声明 - 而不是作为类的成员。

As you can see in the above example, int x is on the stack because it is declared in a method body--not as a member of a class.

这篇关于Java原语是在堆栈还是堆上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆