Java内存分配 [英] Java memory allocation
本文介绍了Java内存分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
java中的"Short"在内存中占据2个字节,数值范围为-32768到32767.
让我们将该类型的变量声明为,
short var;
var = 5;
现在,该值5也在字节"数据类型的范围内(从-128到127),但由于它是短"变量,因此仍在内存中占据2个字节.
为什么在处理此类情况以有效利用内存时Java不允许隐式类型转换?
"Short" in java occupies 2 bytes in memory with numeric range as -32768 to 32767 .
Let''s declare a variable of that type as,
short var ;
var=5;
Now, this value 5 also comes under the range of "Byte" datatype(from -128 to 127) ,but still it occupies 2 bytes in memory as it is a "short" variable.
Why did java not allowed implicit typecasting while dealing with such scenarios to make efficient use of memory?
推荐答案
在将来的某个时间点,您将1000分配给并将其存储在 byte
中?
您会破坏内存!
这些选择都是经过深思熟虑后做出的,除非您已经检查了所有内容并且提供了更好的东西,否则请不要质疑它们.
What in a future point in time you assign 1000 to yourvar
and it was stored in abyte
?
You would corrupt the memory!
These choices were made with a lot of thinking behind them, please do not question them unless you have checked everything, and are offering something better.
类型转换不会产生任何区别,因为var
声明为short
类型,因此在程序运行时无法进行更改.考虑类似的东西:
Typecasting would not make any difference asvar
is declared as ashort
type so it cannot be changed as the program is running. Consider something like:
short var;
var = 5;
// ...
// do some processing
// ...
var = 300;
// what happens now if var had been dynamically changed to byte?
这篇关于Java内存分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文