Thursday 5 May 2011

If Java does not have pointers, why is there a "NullpointerException"?

Its a common statement we keep hearing that Java doesn't have pointers. Well its actually untrue, Java has pointers but is never referred to has pointers and we cannot manipulate them.


A simple example can explain how pointers are used in Java.


Object a = new Object(), b=a;


In the above statement a,b are pointers to a single object in memory. Operations performed on a or b effects the same object.


Java has a set of Primitive types for whom this behavior  doesn't apply. Consider


int i1 =10, i2= i1;
System.out.println(" i1 ="+i1+"i2="+i2) ;
i2=6;
System.out.println(" i1 ="+i1+"i2="+i2) ;

The primitive variable i2 initially holds the copy of the value held by variable i1. Changing value of i1 or i2 will not effect the values of each other. For a Java VM  i1 and i2 are two different 32 bit memory locations. One exception to this is arrays of primitive types. Behavior of arrays are similar to what I'll be explain in the below example


Now consider:


public class Value{int val1;}
Value v1=new Value(10), v2=v1;
System.out.println("v1 ="+v1.val1+"v2="+v2.val1) ;
v2.val1=100;
System.out.println("v1 ="+v1.val1+"v2="+v2.val1) ;


v2 has a copy of the address pointed by v1, hence v1 and v2 point to the same object. Changes made to object of class Value using v1 can also be accessed using v2.

No comments:

Post a Comment