java中的变量声明和内存分配 [英] variable declaration and memory allocation in java

查看:97
本文介绍了java中的变量声明和内存分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来自C / C ++背景,对java很新,我很难理解java中的变量声明和内存分配。

I am from a C/C++ background and very new to java, I am having difficulty in understanding variable declaration and memory allocation in java.

当我们写的时候,

myclass myobject;

我们声明myobject是myclass类型的变量。我们没有为它分配内存。

we declare that myobject is a variable of type myclass. We are not allocating memory to it.

int a;

它声明变量a并且还在堆栈中分配等于int大小的内存。

It declares the variable a and also allocates memory equal to size of int in stack.

是这样的吗?编译器是否为原始数据类型分配内存而不为非原始数据类型分配内存?

Is it the case? Does the compiler allocate memory for the primitive data types but not for the non-primitive data types?

我提出了类似的怀疑在其他地方

推荐答案


编译器不分配内存。它的JVM分配内存

Compiler does't allocate memory. Its JVM who allocate memory

对于原始数据类型,在声明那些变量时分配内存,并在该函数本地获取内存堆。

int x;

For primitive data type memory is allocated at time of declaration of those variable and memory is taken in that function local stack.
int x;


分配的内存in stack 4 byte

memory allocated in stack 4 byte

当我们使用new运算符时,内存被分配给堆,这是类的数据成员的大小。

MyClass对象;

When we use new operator then memory is allocated to heap which is the size of class's data member.
MyClass object;


这是引用变量也需要大小为4字节

This is reference variable also takes size of 4 byte

object = new MyClass();


new运算符在堆中分配内存,size是所有单个
数据成员的类大小的总和。

new operator allocate memory in heap and size is sum of all individual data member's size of that class.

这篇关于java中的变量声明和内存分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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