问题描述
我来自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?
我提出了类似的怀疑。
推荐答案
对于原始数据类型,在声明那些变量时分配内存,并在该函数本地获取内存堆。
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;
当我们使用new运算符时,内存被分配给堆,这是类的数据成员的大小。
MyClass对象;
When we use new operator then memory is allocated to heap which is the size of class's data member. MyClass object;
object = new MyClass();
这篇关于java中的变量声明和内存分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!