Java Primitive and Reference data type difference.

Introduction:

In Java, data types are categorized into two groups; Primitive and Reference data type.

Reference types are also know as non-primitive data type

  • Example of primitive data types are : init, float , double etc
  • Example of reference types : String , user classes , Arrays etc ( Things which can be instantiated (means to be able to create an instance or obj)

There are 3 types of ‘reference types’: (For more details goto : Here)

  • class types − All class object
  • array types − All arrays.
  • interface types − classes that implements interface

There are 8 types of ‘Primitive types’: (For more details goto : Here )

  • boolean data type
  • byte data type
  • char data type
  • short data type
  • int data type
  • long data type
  • float data type
  • double data type

Both primitive and reference variable need to be initialised when declared as method variable. If declared as class variable or static variable, it will have the default value of ‘0’ and ‘null respectively.

Differences:

FeaturePrimitiveReferenced
Default Value zero (0)
Note: for char its 0 in decimal
Read more on default value at : Oracle
null
Assignment (a=b) Creates a new memory location with the value same as ‘b’ .

Changes in ‘a’ does not affect ‘b’
No memory location is created, only the pointer to memory location of b is passed.

Both a and b will be referring to same object, so changes in a reflects in b.

Example:

int test1[] = {1,2,3,4,5,6,7};
int test2[]=test1;
test2[4]=10;
System.out.print(Arrays.toString(test1));

will change ‘5th’ element both test1 and test2.

Note: you have to ‘import java.util.Arrays;’
Return valueReturns only the valueReturns the pointer to memory location ( a pointer is the reference to actual object)
Passing to Methodpasses the valuepasses the handler/ pointer
Comparison (a==b)Compares valueCompares memory location

Example:
int a1[]={1,2};
int a2[]={1,2};
System.out.print(a1==a2);

Will give false. So use methods like equals(), compareTO() : Read here
Stack vs HeapVariables are stored in stack memory


Note: Scope of the variable also plays a role, all local variables are created in heap even the primitive ones . If they are global variable then is created in stack.
The actual object is created in heap memory and handled by garbage manager.

All reference objects are created in stack

Note: Scope of the variable also plays a role, all local variables are created in heap even references. If they are global variable then reference variable will be created in stack and the actual object will be in heap.

MemoryLesser memory requirementMore memory requirement