Although everything in Java is an object, there is one special case in which the so-called "primitive types" are not created by the keyword new because new places object on the heap, which is inefficient especially for a small and simple varialbe. Instead, just like the approach taken by C and C++, an "automatic" variable is created and placed on the stack so it's much more efficient. These primitive types include: boolean, char, byte, short, int, long, float, double and void.
1. How to create
primitive types: char c = 'x';
other objects: String s = new String ("a string");
2. Where to live
primitive types: stack
other objects: heap
3. How long to live
primitive types: only between a pair of curly braces. For example:
{
int x = 12; // only x available
{
int y = 0; // both x and y available
}
// only x available, y out of scope
} // x out of scope
other objects: the reference vanishes at the end of scope, but the object that the reference was pointing to still stays on the heap and thus can later be passed around and duplicated during the course of a program. For example:
{
String s = new String ("a string");
} // end of scope
The reference s is out of scope, but the String object is still occupying memory and will be taken care of by the garbage collector . If an object is not being referenced anymore, the garbage collector will release the momery for new objects.
本文详细解释了Java中原始类型与对象的区别,包括如何创建原始类型、它们的生存位置、存活时间以及如何处理原始类型和对象的不同生命周期。

512

被折叠的 条评论
为什么被折叠?



