Sunday, July 6, 2014

Primitives and references in Java

1. There are two kinds of data values that can be stored in variables namely primitive values and reference values.

2. The primitive types are the numeric types (byte, short, char, int, long, float and double) and boolean. Primitives hold the value directly.

3. The reference types are class and interface types, and array types - keep in mind that all arrays are treated as objects.

4. Each of the primitive types has a corresponding wrapper class - primitive types can be AUTOMATICALLY INTERCONVERTED to objects of their corresponding wrapper classes - a process called autoboxing/unboxing. 

Primitive types and their corresponding wrapper classes:
  
  • byte       ---> Byte
  • short      ---> Short
  • char       ---> Character
  • int           ---> Integer
  • long        ---> Long
  • float        ---> Float
  • double    ---> Double
  • boolean  ---> Boolean

4. String is a class, not a primitive type.

5. A char[] (a character-array) is not the same as a string but both can be inter-converted. 

6. Java uses references to store addresses of objects (as opposed to pointers in C++). 

7. Multiple references may point to the same object. There may be objects in the memory which are not tied to any references (and will probably be garbage-collected).

What is garbage collection?

Garbage collection means reclaiming unused memory in the heap space. Objects are tied to references. When an object is not, the runtime guesses that it is of no use further in the program and treats it as garbage. Such objects MAY OR MAY NOT BE destroyed to reclaim memory. This process cannot be controlled by the programmer. 

Consider this:


 class SomeClass{}  
 public class ReferencesTest{   
   public static void main(String[] array){   
     SomeClass obj1 = new SomeClass();    //1         
     new SomeClass();                     //2  
     SomeClass obj2 = obj1;               //3  
     obj1 = null;                         //4  
     SomeClass obj3;                      //5  
   }   
 }   



At line 1 we are creating a new SomeClass object which can be manipulated using variable obj1. Put another way, obj1 stores the address (and other memory-related data) for that SomeClass object.

At line 2 we create another SomeClass object which is not tied to any reference (and thus eligible for garbage collection). This object is different from that created in line 1. 



At line 3 we are creating a new reference variable obj2 that points to the same SomeClass object as obj1



So far we have created 2 SomeClass objects.


Now at line 4, obj1 is made null - it is not referring to any object now. Keep in mind that the SomeClass object created at line 1 is still there (being referred to by obj2).

At line 5 we created a new SomeClass reference obj3 (which must be initialized or assigned to an object before it is used since it is a local variable).