Prefer primitives over boxed primitives in java

This blog is one of the item in famous "Effective Java 2/e" by Joshua Bloch.

In java, we got a flexibility of auto boxing and auto-unboxing of Java primitives like int,long,boolean etc..,

int i=0;
Integer j = i;

In the above example i is autoboxed to j and the vice-versa is also possible.

Consider the following example:

public class TestClass {

private static Integer i;

public static void main(String[] args) {

if(i == 42) {
System.out.println("Unbelievable");
}
}
}
If the above program is executed, what do you expect? it prints "unbelievable" ? no it wiil not but it behaves as strange are printing "unbelievable". It throws NullPointerException !!.

What might be the reason? well this is caused because of one of the side effects of famous auto-boxing. When ever a primitive and boxed primitive involves in an operation, then auto-unboxing of boxed primitive happens.

In the above example, i will be auto unboxed and it is a null reference so it throws NPE. So becareful while using auto boxing.

Comments

A said…
The program actually does not compile, as i is not initialized, and the compiler catches this.
amar said…
Yes Rish, Integer should be declared as static field in class. I will make the changes.

Popular posts from this blog

Proper way to have an anchor tag with onclick event

My FIRE Journey

CORS issues with IE9 and workarounds