Saturday, June 29, 2019

Autoboxing and Unboxing in Java



https://effective-java.com/2010/05/the-advantages-and-traps-of-autoboxing/
1. Can lead to unexpected behaviour
The usage of autoboxing can lead to difficult to recognize errors. Especially if you mix wrapper with primitives in ‘equals’/’==’.
For Example this:
1
2
3
Long l = 0L;
System.out.println(l.equals(0L));
System.out.println(l.equals(0));
Results into
1
2
true
false
2. Hiding
It hides the object creation, which can lead to a big performance loss. For example:
1
2
3
4
Integer counter = 0;
for(int i=0; i < 1000; i++) {
    counter++;
}
What does ‘counter++’?
It gets the primitive int of the Integer and adds one, that it converts back to a “new” Integer (not necessarily, if the Integer cache contains this Integer).
In Java 1.4 it would look like:
Integer.valueOf(counter.intValue() + 1)
3. Overloading
1
2
3
4
5
6
7
8
9
10
11
public static void main(String[] args) throws Exception
{
Integer l = 0;
fubar(l);
}
static void fubar(long b) {
System.out.println("1");
}
static void fubar(Long b) {
System.out.println("2");
}
The result is 1. Because there is no direct conversion from Integer to Long, so the “conversion” from Integer to long is used.
I myself stumbled across one of these errors in an simple “if”. But I don’t know anymore, how the error looked like. A other completely independent team in our company had a similar experience and they forbid to use Autoboxing in their project, too.

http://java-tweets.blogspot.com/2012/04/pitfalls-of-autoboxing-and-unboxing.html

Unboxing a null value. 



Since the compiler generates a call to primitiveValue(), a NullpointerExceptionexception occurs when unboxing an null wrapper class's reference to its primitive type.For example, the code will compile but it will throw a NullpointerException at runtime. 

Long lobj = null;
long l = lobj;

The reason for this exception is, the compiler replaces the unboxing code 
long l = lobj; with equivalent long l=lobj.longValue(); during compile time.So the method invocation on null, null.longValue() throws NullPointerException at runtime.

Primitive types can not be widened/Narrowed to the Wrapper classes and vice versa. 


Notice that primitive types can't be widened/narrowed to the wrapper objects.The wrapper objects can be widened to primitive types but narrowing is not possible.

Autoboxing is not Recommended for Scientific Calculations.


 Autoboxing and auto-unboxing process is expensive.For example, the code d = a * b + c is using Integer classes for abc and d, and the generated code is d.valueOf(a.intValue() * b.intValue() + c.intValue()). All these method invocations have their own overhead, so it’s usually recommended to use autoboxing when needed to store primitives in collections. 

Widening takes priority than boxing

Boxing takes priority than Varargs

https://beginnersbook.com/2014/09/java-autoboxing-and-unboxing-with-examples/
http://edayan.info/java/autoboxing-and-unboxing-in-java/
Why do we need Autoboxing and Unboxing?
  • To use them in generics. Java generic types only accepts objects. So if you want to use int or byte in a collection of generic type we need to convert them to corresponding wrapper classes.
  • To Convert primitives from/to String objects or to convert to other radix(base) like hexadecimal, octal etc.
  • To perform some functions which is available only “Object” form such as .equals()hashcode() on a primitive data type.
  • To perform some operations such as “unary plus”, “unary minus” etc. on a wrapper object.
  • To create more readable code in less keystroke.
http://edayan.info/java/4-things-to-remember-on-autoboxing-and-unboxing
2. Mixing primitive and wrapper in relational or equality operator
If we use a wrapper object to compare against a primitive using relational operator (like “<" or ">“) the unboxing of that wrapper can cause NullPointerException.

https://jimlife.wordpress.com/2007/08/13/integer-byte-long-constant-pool-in-java/
Following the topic about constant pool.
Let’s look inside the source code JDK 1.6, java\lang\Integer.java :
public static Integer valueOf(int i) {
final int offset = 128;
if (i >= -128 && i <= 127) { // must cache
return IntegerCache.cache[i + offset];
}
return new Integer(i);
}
From the source we can see when the value is -128 to 127 it’ll using cache / constant-pool.
So when we run the following code:
Integer i = 20;
Integer i2 = 20;
Integer i3 = 170;
Integer i4 = 170;
System.out.println(“i==i2 : ” + (i==i2) ); // true
System.out.println(“i==i2 : ” + (i3==i4) ); // false
Only value -128 until 127 will be cache. And of course the operator new wil create new object : new Integer(10)!=10.
https://stackoverflow.com/questions/22779145/java-primitive-data-type-on-stack-or-heap
Only local primitive variables and references to object (i.e. variable declared in method) are stored in stack. Others are stored in heap

https://effective-java.com/2015/01/autoboxing-performance/
Boxing is still quiet fast. I suggest to use primitives for mandatory attributes in a object, for heavy CPU calculations and for last resorts in bottleneck fights.
I wouldn’t recommended to use primitives for optional attributes, because that creates evil magic numbers. Of course in very rare cases where every tiny bit of performance counts this might be needed too.
We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%.
https://www.javalobby.org/java/forums/t64731.html

Labels

Review (572) System Design (334) System Design - Review (198) Java (189) Coding (75) Interview-System Design (65) Interview (63) Book Notes (59) Coding - Review (59) to-do (45) Linux (43) Knowledge (39) Interview-Java (35) Knowledge - Review (32) Database (31) Design Patterns (31) Big Data (29) Product Architecture (28) MultiThread (27) Soft Skills (27) Concurrency (26) Cracking Code Interview (26) Miscs (25) Distributed (24) OOD Design (24) Google (23) Career (22) Interview - Review (21) Java - Code (21) Operating System (21) Interview Q&A (20) System Design - Practice (20) Tips (19) Algorithm (17) Company - Facebook (17) Security (17) How to Ace Interview (16) Brain Teaser (14) Linux - Shell (14) Redis (14) Testing (14) Tools (14) Code Quality (13) Search (13) Spark (13) Spring (13) Company - LinkedIn (12) How to (12) Interview-Database (12) Interview-Operating System (12) Solr (12) Architecture Principles (11) Resource (10) Amazon (9) Cache (9) Git (9) Interview - MultiThread (9) Scalability (9) Trouble Shooting (9) Web Dev (9) Architecture Model (8) Better Programmer (8) Cassandra (8) Company - Uber (8) Java67 (8) Math (8) OO Design principles (8) SOLID (8) Design (7) Interview Corner (7) JVM (7) Java Basics (7) Kafka (7) Mac (7) Machine Learning (7) NoSQL (7) C++ (6) Chrome (6) File System (6) Highscalability (6) How to Better (6) Network (6) Restful (6) CareerCup (5) Code Review (5) Hash (5) How to Interview (5) JDK Source Code (5) JavaScript (5) Leetcode (5) Must Known (5) Python (5)

Popular Posts