Integer文字所在的位置在哪里? [英] where is Integer literal resides?

查看:58
本文介绍了Integer文字所在的位置在哪里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下代码片段中:



整数var = new整数(2);

int var1 = 2;



是否真的存在于堆栈上的var1值。

而且,var是对文字2的引用。

但文字2在哪里?

在堆中或在文字池中还是在常量池中?

in the following code snippet :

Integer var = new Integer(2);
int var1 = 2;

is it true that value of var1 exists on stack.
And,var is a reference to literal 2.
But where is literal 2 resides??
in heap or in literal pool or in constant pool?

推荐答案

在我看来就像你在学校得到的一个问题。但没关系。



这两个文字都存储在.DATA部分中(我不知道java中这一部分的确切名称,但它会是相似的。)其实,智能编译器只会存储文字2一次并引用它两次。只要变量没有改变,就不需要复制数据,只需复制参考。简单数据类型(如int)不使用引用,因为它们适合处理器寄存器并因此而值(如果需要,您可以明确地否决它)。



因为你明确将文字2装入var作为整数,所以你强制编译器创建一个对象来保存这个文字。这是包含它的框,因此名称装箱(和拆箱)。对象始终存储在堆中。简单类型(如int)和引用(也是一种简单类型)存储在堆栈中。 (这不适用于c / c ++,因为它可以容纳复杂类型,如堆栈上的结构,但这是另一个故事)



希望你得到这个想法。



祝你好运!
Looks to me like a question you got at school,. but okay.

Both these literals are stored in a .DATA section (I don''t know the exact name of this section in java but it will be something alike.) Actually, a smart compiler would only store the literal 2 once and reference it twice. As long a the variable isn''t changed there is no need to copy the data, only the reference. Simple data types (like int) don''t use a reference because they fit into a processor register and are therefor by value (You could explicitly overrule this if necessary).

Because you are explicitly boxing the literal 2 into var as integer, you force the compiler to create an object to hold this literal. This is the box that holds it, therefor the name boxing (and unboxing). Objects are always stored in the heap. Simple types (like int) and references (also a simple type) are stored on the stack. (this doesn''t apply to c/c++ because it can hold complex types like structs on the stack, but that''s another story)

Hopefully you get the idea.

Good luck!


这篇关于Integer文字所在的位置在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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