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.
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.
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