Wednesday, November 18, 2015

Difference between Primitive and Reference variable in Java

There are two types of variables in Java, primitive and reference type. All the basic types e.g. int, boolean, char, short, float, long and double are known as primitive types. JVM treats them differently than reference types, which is used to point objects e.g. String, Thread, File and others. Reference variables are not pointers but a handle to the object which are created in heap memory. Main difference between primitive and reference type is that, primitive type always has a value, it can never be null but reference type can be null, which denotes absence of value. So if you create a primitive variable of type int and forget to initialize it then it's value would be 0, the default value of integral type in Java, but a reference variable by default has null value, which means no reference is assigned to it. If you try to access any field or invoke a method on null reference, you will be greeted with NullPointerException in Java. It's very important for every Java developer to understand difference between primitive and reference variable in different cases e.g. while assigning values, comparing values, passing them as method arguments and returning them from methods, to avoid nasty errors e.g. null pointer exception. In short, main difference between two types is that primitive types stores actual values but reference type stores handle to object in heap

Passing primitive and reference variable as method argument
 
When you pass primitive values to a method the values are passed to method, but when you pass reference variable, only handle is copied. which means for primitives, changing the formal parameter's value doesn't affect the actual parameter's value, while in case of reference types, changing the formal parameter's handle doesn't affect the actual parameter's address but changing the formal parameter's internal values does affect actual parameter's object, because they refer to same object in memory.

No comments:

Post a Comment