Java 内存中到底什么是 null [英] What exactly is null in Java memory

查看:27
本文介绍了Java 内存中到底什么是 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我声明一些像

String str = null; 

  • 是否为变量 str 分配了内存?
  • 如果分配了,会分配多少字节?
  • 如果没有分配,JVM怎么知道有一个名为str的变量被声明了?
  • 如果已经分配,​​如果内存中有null值,那么null的二进制表示究竟是什么?
    • Is there memory allocated for variable str?
    • If allocated, how many bytes will be allocated?
    • If not allocated, how does the JVM know that there is some variable called str been declared?
    • If allocated and if there is null value inside the memory, then what exactly is the representation of null in binary?
    • 推荐答案

      当您执行以下操作时:

      String str = null;
      

      唯一分配的是对字符串的引用(这类似于包含指针类型的语言中的字符串指针).此引用是一个 32 位或 64 位变量(取决于您的硬件架构和 Java 版本),它驻留在堆栈中(可能取决于您的声明所在的确切上下文).

      The only thing allocated is a reference to a string (this is analogous to a string-pointer in languages which contain pointer-types). This reference is a 32 or 64 bit variable (depending upon your hardware architecture and Java version) which resides on the stack (probably, depending upon the exact context in which your declaration is placed).

      不应为 null 本身分配内存,因为 null 实际上不是有效的对象实例.它只是一个占位符,指示对象引用当前未引用对象.可能它只是字面值 0,这样将对象引用分配给 null 相当于在 C/中将指针类型设置为 NULLC++.但最后一点是我的猜测.

      No memory should be allocated for the null itself, because null is not actually a valid object instance. It is simply a placeholder that indicates that the object reference is not currently referring to an object. Probably it is simply the literal value 0, such that assigning an object reference to null is equivalent to setting a pointer type to NULL in C/C++. But that last bit is conjecture on my part.

      这篇关于Java 内存中到底什么是 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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