Difference Betwixt Primitive As Well As Reference Variable Inward Java

Advertisement

Masukkan script iklan 970x90px

Difference Betwixt Primitive As Well As Reference Variable Inward Java

Sabtu, 18 Juli 2020

There are 2 types of variables inwards Java, primitive together with reference type. All the basic types e.g. int, boolean, char, short, float, long and double are known every bit primitive types. JVM treats them differently than reference types, which is used to signal objects e.g. String, Thread, File and others. Reference variables are non pointers but a grip to the object which is created inwards heap memory. The principal departure betwixt primitive together with reference type is that primitive type ever has a value, it tin give notice never live null but reference type tin give notice live null, which denotes the absence of value. So if y'all exercise a primitive variable of type int together with forget to initialize it together with thence it's value would be 0, the default value of integral type inwards Java, but a reference variable yesteryear default has a null value, which agency no reference is assigned to it.


If y'all essay to access whatever acre or invoke a method on a null reference, y'all volition live greeted alongside NullPointerException inwards Java. It's real of import for every Java developer to sympathize difference betwixt primitive together with reference variable inwards dissimilar cases e.g. piece assigning values, comparison values, passing them every bit method arguments together with returning them from methods, to avoid nasty errors e.g. null pointer exception.

In short, the principal departure betwixt 2 types is that primitive types shop actual values but reference type stores grip to object inwards the heap. Head First Java s Edition every bit good explains this fundamental concept clearly, So y'all tin give notice every bit good guide hold a await in that place to sympathize it fleck more.

 There are 2 types of variables inwards Java Difference betwixt Primitive together with Reference variable inwards Java



Difference betwixt Primitive vs Reference variable

Now, nosotros know the role of both types of variable, its fourth dimension to guide hold a deep dive into roughly to a greater extent than differences betwixt primitive together with reference variables inwards Java.



Default value together with Null
First departure betwixt primitive together with reference type is that former tin give notice never live null if no value is assigned they guide hold their default value e.g. boolean variable volition live initialized alongside false, byte, short, char,int and long will live initialized alongside zero, together with float together with double variables volition live initialized alongside 0.0 value inwards Java.

Here is a classification of all primitive together with reference type inwards Java :

 There are 2 types of variables inwards Java Difference betwixt Primitive together with Reference variable inwards Java


What exercise they store?
The minute departure is that primitive types stores values but reference type stores handle to object inwards heap space. Remember, reference variables are non pointers similar y'all powerfulness guide hold seen inwards C together with C++, they are simply a grip to object thence that y'all tin give notice access them together with brand roughly alter on object's state.



Assigning value using Assignment Variable (=)
When y'all assign a value to primitive information types, the primitive value is copied, but when y'all assign an object to reference type, the grip is copied. which agency for reference type object is non copied only the grip is copied, i.e. the object is shared betwixt 2 reference variable, known every bit aliases. An implication of this is change done yesteryear i variable volition deport on to other.

int i = 20; int j = i; j++; // volition non deport on i, j volition live 21 but i volition nevertheless live 20  System.out.printf("value of i together with j after change i: %d, j: %d %n", i, j);  List<String> listing = new ArrayList(2); List<String> re-create = list;    copy.add("EUR"); // adding a novel chemical ingredient into list, it would live visible to both listing together with copy System.out.printf("value of listing together with re-create after change list: %s, copy: %s %n", list, copy);  Output : value of i together with j after change i: 20, j: 21  value of listing together with re-create after change list: [EUR], copy: [EUR]

You tin give notice encounter that change on i primitive variable doesn't deport on the re-create but it does inwards the illustration of the reference variable. This sometimes creates confusion betwixt programmer that Java is non passed yesteryear value for the reference type, which is non correct, Java is ever passed yesteryear value, live it references or primitive variables.

Here is a diagram which clearly shows the departure most how assignment operator industrial plant differently on primitive together with reference variable inwards Java :

 There are 2 types of variables inwards Java Difference betwixt Primitive together with Reference variable inwards Java


Comparison using == operator
When y'all compare primitive variables using equality (==) operator, their primitive values are compared but when y'all compare reference variable, their address is compared, which agency 2 objects which are logically equal e.g. 2 String object alongside same content may live seen every bit non equal, every bit seen below :

int i = 20; int j = 20;  if (i == j) {     System.out.println("i together with j are equal"); }  String JPY = new String("JPY"); String YEN = new String("JPY");  if (JPY == YEN) {     System.out.println("JPY together with YEN are same"); }  if (JPY.equals(YEN)) {     System.out.println("JPY together with YEN are equal yesteryear equals()"); }  Output : i together with j are equal JPY together with YEN are equal yesteryear equals()

You tin give notice encounter that primitive variable are rightly compared using == operator, but when nosotros compared 2 String object alongside same contents i.e. "JPY", they are non equal using == operator, that's why the minute trace of piece of job is non printed, but when I compared them using equals() method, they are considered equal. This agency y'all should always utilisation equals() method to compare reference types.


Passing primitive together with reference variable every bit method argument
When y'all overstep primitive values to a method the values are passed to the method, but when y'all overstep reference variable, only the grip is copied. which agency for primitives, changing the formal parameter's value doesn't deport on the actual parameter's value, piece inwards illustration of reference types, changing the formal parameter's grip doesn't deport on the actual parameter's address but changing the formal parameter's internal values does deport on actual parameter's object, because they refer to the same object inwards memory. See Core Java Volume 1 tenth Edition yesteryear Cay S. Horstmann to larn more.

 There are 2 types of variables inwards Java Difference betwixt Primitive together with Reference variable inwards Java


For those, who are non aware of formal together with actual parameters, formal parameters are those, which is listed(along alongside its type) inwards method proclamation e.g. on getName(Employee e) , e is a formal parameter. While actual parameters are those which are passed to method during invocation e.g. getName(new Employee("John")).

Here is the proof of I simply said :

/**  * Program to demonstrate departure betwixt primitive together with reference type  * variable inwards Java.  *   * @author WINDOWS 8  *  */ public class PrimitiveVsReference{      private static class Counter {         private int count;          public void advance(int number) {             count += number;         }          public int getCount() {             return count;         }     }      public static void main(String args[]) {                 int i = 30;         System.out.println("value of i earlier passing to method : " + i);         print(30);         System.out.println("value of i after passing to method : " + i);                  Counter myCounter = new Counter();         System.out.println("counter earlier passing to method : " + myCounter.getCount());         print(myCounter);         System.out.println("counter after passing to method : " + myCounter.getCount());     }      /*      * impress given reference variable's value      */     public static void print(Counter ctr) {         ctr.advance(2);     }          /**      * impress given primitive value      */     public static void print(int value) {         value++;     }  }  Output : value of i earlier passing to method : 30 value of i after passing to method : 30 counter earlier passing to method : 0 counter after passing to method : 2 

You tin give notice encounter that changing formal parameter's value doesn't deport on actual parameter's value inwards illustration of primitive variable but it does inwards the illustration of the reference variable, but exclusively if y'all alter the land of an object.


Return value of a method
When y'all provide primitive types from a method together with thence the primitive value is returned but when y'all provide a reference type, i time to a greater extent than exclusively grip to the is returned. This agency a locally created object tin give notice live on fifty-fifty after method finishes its execution, if it was returned from a method or if it was stored inwards whatever fellow member variable, why? because object is ever created inwards heap memory. piece all primitive local variables are destroyed after method finishes execution.


Stack vs Heap
Primitive variables are created inwards the stack piece reference variable is created inwards heap space, which is managed yesteryear Garbage Collector. See the difference betwixt stack together with heap retentivity inwards Java, for to a greater extent than details.


Memory consumption or Size
Primitive variables guide hold less retentivity than reference variable because they don't involve to hold object metadata e.g. object header. An int primitive variable volition guide hold less retentivity than Integer object for storing same value e.g. 5.


That's all most the difference betwixt primitive together with reference variable inwards Java. Always recollect that primitive variables are yesteryear default initialized to their default value, which is non null together with they volition non throw NullPointerException, but if y'all access an uninitialized reference variable it volition throw NullPointerException.

Primitive variables are every bit good copied when y'all assign them to roughly other primitive variable together with alter on i variable volition non deport on other, but inwards the illustration of the reference variable, the grip is shared betwixt multiple reference variable together with whatever alter into object's land volition live visible to all reference variable.

Another fundamental departure betwixt primitive together with reference variable to depository fiscal establishment annotation is that sometime guide hold less retentivity than afterwards due to object metadata overhead e.g. retentivity require belongings object header. An int primitive variable volition ever guide hold less retentivity than Integer object for storing same value.

Further Learning
Complete Java Masterclass
answer)
  • Difference betwixt SOAP together with REST Web Service inwards Java? (answer)
  • Difference betwixt HashMap, TreeMap together with LinkedHashMap inwards Java? (answer)
  • What is the departure betwixt direct, non-direct together with mapped buffer inwards Java? (answer)
  • What is the departure betwixt Factory designing together with dependency Injection? (answer)
  • How exercise y'all calculate the departure betwixt 2 dates inwards Java? (answer)
  • Difference betwixt Composition together with Inheritance inwards OOP? (answer)
  • 10 differences betwixt JavaScript together with Java? (answer)
  • Difference betwixt Maven, ANT together with Jenkins inwards Java footing (answer)
  • Difference betwixt ArrayList together with LinkedList inwards Java? (answer)
  • What is departure betwixt transient together with volatile variable inwards Java? (answer)
  • Some fundamental departure betwixt Vector together with ArrayList inwards Java? (answer)
  • Difference betwixt get() together with load() method inwards Hibernate? (answer)