JVM在声明时为原始类型分配内存,而不为非原始类型分配内存吗? [英] JVM allocates memory at declaration for primitive types, but not for non-primitive types?

查看:50
本文介绍了JVM在声明时为原始类型分配内存,而不为非原始类型分配内存吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来自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?

我在此处也提出了类似的疑问.

I've raised a similar doubt here.

推荐答案

编译器不分配内存.分配内存的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;

在堆栈4字节中分配的内存

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运算符在堆中分配内存,并且大小是所有个体的总和该类的数据成员的大小.

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

这篇关于JVM在声明时为原始类型分配内存,而不为非原始类型分配内存吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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