Java - 空变量是否需要内存空间 [英] Java - Does null variable require space in memory

查看:26
本文介绍了Java - 空变量是否需要内存空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码块:

class CheckStore {
    private String displayText;
    private boolean state;
    private String meaningfulText;
    private URL url;

    public CheckStore(String text, boolean state) {
        this.displayText = text;
        this.state = state;
    }
    :
    :
}

当我在构造函数中初始化两个变量(displayTextstate)时,做另外两个变量(meaningfulTexturl) 需要内存空间来存储 null 值?

When I initialize two variables (displayText and state) in the constructor, do the other two variables (meaningfulText and url) require space in the memory to store null value?

第一季度.如果它们确实需要空间,null 值在内存中占用多少内存?(例如,int 需要 4 个字节).

Q1. If they do require space, how much memory does a null value take in the memory? (ex. int takes 4 bytes).

第 2 季度.一个字符串在内存中占用多少空间?一个字符串占用多少内存空间?它取决于字符串的长度吗?

Q2. How much space does a string take in memory? How much memory space does a string take? Does it depend on the length of the string?

推荐答案

在 Java 中,null 只是一个引用(基本上是一个受限制的指针)可以拥有的值.这意味着该引用不涉及任何内容.在这种情况下,您仍然会占用参考空间.这是 32 位系统上的 4 个字节或 64 位系统上的 8 个字节.但是,在您实际分配该类的实例以指向该引用之前,您不会为该引用所指向的类消耗任何空间.

In Java, null is just a value that a reference (which is basically a restricted pointer) can have. It means that the reference refers to nothing. In this case you still consume the space for the reference. This is 4 bytes on 32-bit systems or 8 bytes on 64-bit systems. However, you're not consuming any space for the class that the reference points to until you actually allocate an instance of that class to point the reference at.

就字符串而言,Java 中的 String 每个字符占用 16 位(2 个字节),加上少量的簿记开销,这可能是未记录的和特定于实现的.

As far as the String, a String in Java takes 16 bits (2 bytes) for each character, plus a small amount of book-keeping overhead, which is probably undocumented and implementation specific.

这篇关于Java - 空变量是否需要内存空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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