Showing posts from November, 2009

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) {
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 throw…

Be careful before setting innerHTML

When working with javascript, the most common thing a developer will do for adding content by setting innerHTML of container element.

ele.innerHTML ='<div><span>This is working fine</span>';
if(user == 'amar') {
ele.innerHTML += '<span>Hello amar welcome to your blog!</span>';


Above code seems to be ok but there is a big mistake. Element's innerHTML is set and the div is not closed before evaluating the condition. Browser closes the div at the point and the span that is added in the condition will be sibling of div instead of child !!.

This problem can be solved by using a variable, adding the content to that variable and finally setting innerHTML to the element.