如果我们只是在java中声明一个没有初始化的变量,会在内存中发生什么? [英] What happens in memory if we just declare a variable without initialization in java?

查看:208
本文介绍了如果我们只是在java中声明一个没有初始化的变量,会在内存中发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们只创建一个引用变量或者为原始数据类型或引用数据类型声明一个变量而不用以下任何值进行初始化,那么内存会发生什么?

What happens in memory if we just create a reference variable or declare a variable for primitive data types or reference data types without initializing with any value as below?

int x;

Employee emp;  

那么两种情况下内存究竟发生了什么?

So what exactly happens in memory in both the cases?

是否在此阶段分配了任何内存,或者它是指向任何随机位置还是指向null或指向垃圾值?

Is any memory allocated at this stage or does it point to any random location or points to null or points to garbage values?

与第二种情况一样,如果我们使用带有new运算符的构造函数或使用任何其他方式创建对象,则只会在内存中创建空格。

As in the 2nd case, only space will created in memory if we create a object using the constructor with new operator or using any other ways like.

Employee emp = new Employee();


推荐答案

Java虚拟机(JVM)从中分配堆内存之后操作系统并为Java应用程序管理自己的堆。当应用程序创建一个新对象(例如 Employee emp = new Employee())时,JVM会分配一个连续的堆内存区域来存储它。

The Java Virtual Machine (JVM) allocates heap memory from the operating system and manages its own heap for Java applications afterwards. When an application creates a new object (e.g. Employee emp = new Employee()), the JVM assigns a continuous area of heap memory to store it.

虽然未初始化对象(例如 Employee emp = null ),但不需要分配任何内存。但是,原始类型(在全局范围内)使用默认值进行初始化,即使您未明确设置它(例如 int x 实际上是 int x = 0 )。所以在这种情况下,也会分配内存。

While an object is not initialized (e.g. Employee emp = null), there is no need to allocate any memory. Primitive types (in the global scope), however, are initialized with a default value, even if you do not set it explicitly (e.g. int x is in fact int x = 0). So in this case, memory will be allocated, too.

只要对象的引用保留在应用程序的任何地方,对象就会保留在内存中。不再引用的对象将由垃圾收集器(GC)处理,并将从堆中清除以回收它们的空间。

As long as a reference to the object is kept anywhere within the application, the object remains in memory. Objects that are no longer referenced will be disposed by the garbage collector (GC) and will be cleared out of the heap to reclaim their space.

String class也分配堆内存,但稍微调整一下: String interning String 实例,就会使用a>。所以,实际上你在内存中只有一个实例,但是引用它的多个变量。

The String class also allocates heap memory, uses a little tweak though: String interning is used, as soon as you allocate multiple instances of String with the same text. So, in fact you will only have one instance in memory, but multiple variables that reference it.

这篇关于如果我们只是在java中声明一个没有初始化的变量,会在内存中发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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