Primitive Types and Objects

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.

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值