Quick reference of Autoboxing in JDK 1.5

Boxing is simply converting primitive type to wrapper class. e.g. Integer intObj = new Integer(100). Autoboxing is compiler taking care of boxing. WIth autoboxing following is a legal statement:
Integer intObj=100;

Vice-versa is called unboxing. JDK 1.5 supports autoboxing and auto-unboxing.

Following is legal with autoboxing
1. Integer intObj1=100; Integer intObj2=200;
2. Integer intObj3=intObj1+intObj2;
3. map.put("zero", 0); //map is defined as Map
4. int z=map.get("zero");
5. Boolean result= (intObj1==intObj2);
6. int intValue = intObj1; //throws nullPointerException
7. foo(intValue); //foo is defined as - public void foo(Integer intObj1){}
8. bar(intObj1); //bar is defined as - public void bar(int intValue){}
9. if(booleanObj){} //booleanObj is of type Boolean
10. int intValue = -intObj1;


Following is illegal
1. Integer intObj=shortVal; // shortVal is of type short
2. Double doubleObj = 10; //Can not convert from int to Double

Advantage of autoboxing and auto-unboxing is concise code. But careless use might result in poor performance of the code. Certain primitives are cached and autoboxing returns same wrapper objects. This value may depend on jvm used, normally this value are:
1. The boolean values true and false.
2. The byte values.
3. The short and int values between -128 and 127.
4. The char values in the range '/u0000' to '/u007F'.

It means, if intObj1=127 and intObj2=127 then intObj1==intObj2 returns true. But, if if intObj1=128 and intObj2=128 then intObj1==intObj2 returns false.

Best practices compiled by Brian Pontarelli at http://brian.pontarelli.com/2004/07/15/jdk-5-auto-boxing-best-practices [3]

If you can use primitives do it, if you can’t don’t.
1. Avoid using wrapper classes whenever possible.
2. Never do math with wrappers.
3. Try not to use any of the comparison operators (<, >, <=, >=, ==, etc) with wrappers.
4. Avoid usage in loop statements.
5. Always check for null values.


References:

[1] SCJP 5 : Chapter 3. API Contents (Part-1) http://www.exforsys.com/content/view/1885/362/
[2] Autoboxing surprises from J2SE 5 http://www.theserverside.com/news/thread.tss?thread_id=27129
[3] JDK 5 - auto-boxing best practices http://brian.pontarelli.com/2004/07/15/jdk-5-auto-boxing-best-practices/
[4] J2SE 5.0 in a Nutshell http://java.sun.com/developer/technicalArticles/releases/j2se15/
[5] Autoboxing http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html
[6] Object type http://en.wikipedia.org/wiki/Autoboxing

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值