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
Quick reference of Autoboxing in JDK 1.5
最新推荐文章于 2021-07-07 14:08:17 发布