Difference Betwixt Primitive As Well As Reference Variable Inwards Java

There are 2 types of variables inward Java, primitive in addition to reference type. All the basic types e.g. int, boolean, char, short, float, long and double are known equally primitive types. JVM treats them differently than reference types, which is used to betoken objects e.g. String, Thread, File and others. Reference variables are non pointers but a handgrip to the object which is created inward heap memory. The primary departure betwixt primitive in addition to reference type is that primitive type ever has a value, it tin flame never live null but reference type tin flame live null, which denotes the absence of value. So if yous practice a primitive variable of type int in addition to forget to initialize it hence it's value would be 0, the default value of integral type inward Java, but a reference variable yesteryear default has a null value, which way no reference is assigned to it.


If yous endeavour to access whatever acre or invoke a method on a goose egg reference, yous volition live greeted alongside NullPointerException inward Java. It's really of import for every Java developer to empathise difference betwixt primitive in addition to reference variable inward dissimilar cases e.g. piece assigning values, comparison values, passing them equally method arguments in addition to returning them from methods, to avoid nasty errors e.g. goose egg pointer exception.

In short, the primary departure betwixt 2 types is that primitive types shop actual values but reference type stores handgrip to object inward the heap. Head First Java 2d Edition equally good explains this telephone substitution concept clearly, So yous tin flame equally good accept a hold off in that place to empathise it fleck more.

 There are 2 types of variables inward Java Difference betwixt Primitive in addition to Reference variable inward Java



Difference betwixt Primitive vs Reference variable

Now, nosotros know the utilization of both types of variable, its fourth dimension to accept a deep dive into to a greater extent than or less to a greater extent than differences betwixt primitive in addition to reference variables inward Java.



Default value in addition to Null
First departure betwixt primitive in addition to reference type is that former tin flame never live null if no value is assigned they accept their default value e.g. boolean variable volition live initialized alongside false, byte, short, char,int and long will live initialized alongside zero, in addition to float in addition to double variables volition live initialized alongside 0.0 value inward Java.

Here is a classification of all primitive in addition to reference type inward Java :

 There are 2 types of variables inward Java Difference betwixt Primitive in addition to Reference variable inward Java


What practice they store?
The bit departure is that primitive types stores values but reference type stores handle to object inward heap space. Remember, reference variables are non pointers similar yous mightiness direct hold seen inward C in addition to C++, they are only a handgrip to object hence that yous tin flame access them in addition to brand to a greater extent than or less alter on object's state.



Assigning value using Assignment Variable (=)
When yous assign a value to primitive information types, the primitive value is copied, but when yous assign an object to reference type, the handgrip is copied. which way for reference type object is non copied only the handgrip is copied, i.e. the object is shared betwixt 2 reference variable, known equally aliases. An implication of this is modification done yesteryear 1 variable volition impact to other.

int i = 20; int j = i; j++; // volition non impact i, j volition live 21 but i volition yet live 20  System.out.printf("value of i in addition to j after modification 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 gene into list, it would live visible to both listing in addition to copy System.out.printf("value of listing in addition to re-create after modification list: %s, copy: %s %n", list, copy);  Output : value of i in addition to j after modification i: 20, j: 21  value of listing in addition to re-create after modification list: [EUR], copy: [EUR]

You tin flame encounter that modification on 1 primitive variable doesn't impact the re-create but it does inward the representative 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 close how assignment operator plant differently on primitive in addition to reference variable inward Java :

 There are 2 types of variables inward Java Difference betwixt Primitive in addition to Reference variable inward Java


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

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

You tin flame 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 bit business is non printed, but when I compared them using equals() method, they are considered equal. This way yous should always utilization equals() method to compare reference types.


Passing primitive in addition to reference variable equally method argument
When yous exceed primitive values to a method the values are passed to the method, but when yous exceed reference variable, only the handgrip is copied. which way for primitives, changing the formal parameter's value doesn't impact the actual parameter's value, piece inward representative of reference types, changing the formal parameter's handgrip doesn't impact the actual parameter's address but changing the formal parameter's internal values does impact actual parameter's object, because they refer to the same object inward memory. See Core Java Volume 1 tenth Edition yesteryear Cay S. Horstmann to larn more.

 There are 2 types of variables inward Java Difference betwixt Primitive in addition to Reference variable inward Java


For those, who are non aware of formal in addition to actual parameters, formal parameters are those, which is listed(along alongside its type) inward method annunciation 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 only said :

/**  * Program to demonstrate departure betwixt primitive in addition to reference type  * variable inward 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 flame encounter that changing formal parameter's value doesn't impact actual parameter's value inward representative of primitive variable but it does inward the representative of the reference variable, but entirely if yous alter the land of an object.


Return value of a method
When yous provide primitive types from a method hence the primitive value is returned but when yous provide a reference type, in 1 lawsuit to a greater extent than entirely handgrip to the is returned. This way a locally created object tin flame live fifty-fifty after method finishes its execution, if it was returned from a method or if it was stored inward whatever fellow member variable, why? because object is ever created inward heap memory. piece all primitive local variables are destroyed after method finishes execution.


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


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


That's all close the difference betwixt primitive in addition to reference variable inward Java. Always hollo upwards that primitive variables are yesteryear default initialized to their default value, which is non goose egg in addition to they volition non throw NullPointerException, but if yous access an uninitialized reference variable it volition throw NullPointerException.

Primitive variables are equally good copied when yous assign them to to a greater extent than or less other primitive variable in addition to alter on 1 variable volition non impact other, but inward the representative of the reference variable, the handgrip is shared betwixt multiple reference variable in addition to whatever alter into object's land volition live visible to all reference variable.

Another telephone substitution departure betwixt primitive in addition to reference variable to banknote is that quondam accept less retentivity than afterward due to object metadata overhead e.g. retentivity require belongings object header. An int primitive variable volition ever accept less retentivity than Integer object for storing same value.

Further Learning
Complete Java Masterclass
answer)
  • Difference betwixt SOAP in addition to REST Web Service inward Java? (answer)
  • Difference betwixt HashMap, TreeMap in addition to LinkedHashMap inward Java? (answer)
  • What is the departure betwixt direct, non-direct in addition to mapped buffer inward Java? (answer)
  • What is the departure betwixt Factory designing in addition to dependency Injection? (answer)
  • How practice yous calculate the departure betwixt 2 dates inward Java? (answer)
  • Difference betwixt Composition in addition to Inheritance inward OOP? (answer)
  • 10 differences betwixt JavaScript in addition to Java? (answer)
  • Difference betwixt Maven, ANT in addition to Jenkins inward Java globe (answer)
  • Difference betwixt ArrayList in addition to LinkedList inward Java? (answer)
  • What is departure betwixt transient in addition to volatile variable inward Java? (answer)
  • Some telephone substitution departure betwixt Vector in addition to ArrayList inward Java? (answer)
  • Difference betwixt get() in addition to load() method inward Hibernate? (answer)
  • 0 Response to "Difference Betwixt Primitive As Well As Reference Variable Inwards Java"

    Post a Comment

    Iklan Atas Artikel

    Iklan Tengah Artikel 1

    Iklan Tengah Artikel 2

    Iklan Bawah Artikel