哪个对象是在内存的哪一部分创建的?

发布于 2024-08-04 19:07:18 字数 642 浏览 2 评论 0原文

public class Order
{
    static Customer cust = new Customer();
    string sEmpty = "";

    public static void main(String args[])
    {
        int iTotal = 10;
        string sProductName = "Salt";
        Ship shp = new Ship();
    }
}

在上面的代码中,哪个对象和引用是在内存的哪一部分创建的? (我的意思是堆和堆栈)

alt 文字
(来源:c-sharpcorner.com)

public class Order
{
    static Customer cust = new Customer();
    string sEmpty = "";

    public static void main(String args[])
    {
        int iTotal = 10;
        string sProductName = "Salt";
        Ship shp = new Ship();
    }
}

At the above code, which object and reference is created in the which part of memory? (I mean Heap and Stack)

alt text
(source: c-sharpcorner.com)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

烧了回忆取暖 2024-08-11 19:07:18

由于您将问题标记为 Java,所以我假设您的意思是 Java。直接从马嘴里说出来:

Java虚拟机有一个堆,所有Java共享
虚拟机线程。堆是
运行时数据区域
所有类实例的内存和
数组已分配。

JVM 规范

这里是 链接到之前的一个SO问题,该问题详细讨论了这个问题(并且是关于该主题的与语言无关的讨论)。

下面是 C# 角的一篇文章的链接,详细介绍了该问题在 C# 中。

Since you tagged your question Java, I'll assume you meant in Java. Straight from the horse's mouth:

The Java virtual machine has a heap that is shared among all Java
virtual machine threads. The heap is
the runtime data area from which
memory for all class instances and
arrays is allocated.

JVM Spec

Here is a link to a previous SO question that goes into this in serious detail (and is a language-agnostic discussion on the topic).

Here's a link to an article from C# corner detailing the issue in C#.

歌入人心 2024-08-11 19:07:18

Order 和 Customer 都在堆上。尽管Customer可能是一个结构体,但它是引用类型(例如,类)的组合成员。

所有字符串都是引用类型并在堆上创建。

我不确定 Ship 类,因为我没有它的声明(即,我不知道它是结构还是类)。

int iTotal 变量在堆栈上创建。

对于 C# 来说也是如此。 Java 可能有不同的规则。

Order and Customer are on the heap. Though Customer may be a struct, it is a composed member of a reference type (e.g., a class).

All strings are reference types and are created on the heap.

I'm not sure about the Ship class because I don't have its declaration (i.e., I don't know if it is a struct or a class).

The int iTotal variable is created on the stack.

This is true for C#. Java may have different rules at play.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文