Difference Betwixt Primitive Together With Reference Variable Inward Java

There are ii types of variables inwards Java, primitive in addition to 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 indicate objects e.g. String, Thread, File and others. Reference variables are non pointers but a handgrip to the object which is created inwards heap memory. The principal departure betwixt primitive in addition to reference type is that primitive type e'er has a value, it tin never live null but reference type tin live null, which denotes the absence of value. So if yous practise a primitive variable of type int in addition to forget to initialize it in addition to then it's value would be 0, the default value of integral type inwards Java, but a reference variable past times default has a null value, which agency no reference is assigned to it.


If yous elbow grease to access whatever patch or invoke a method on a cypher reference, yous volition live greeted amongst NullPointerException inwards Java. It's real of import for every Java developer to empathize difference betwixt primitive in addition to reference variable inwards unlike cases e.g. patch assigning values, comparison values, passing them every bit method arguments in addition to returning them from methods, to avoid nasty errors e.g. cypher pointer exception.

In short, the principal departure betwixt ii types is that primitive types shop actual values but reference type stores handgrip to object inwards the heap. Head First Java s Edition too explains this telephone substitution concept clearly, So yous tin too guide hold a hold off at that topographic point to empathize it chip more.

 There are ii types of variables inwards Java Difference betwixt Primitive in addition to Reference variable inwards Java



Difference betwixt Primitive vs Reference variable

Now, nosotros know the locomote of both types of variable, its fourth dimension to guide hold a deep dive into about to a greater extent than differences betwixt primitive in addition to reference variables inwards Java.



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

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

 There are ii types of variables inwards Java Difference betwixt Primitive in addition to Reference variable inwards Java


What practise 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 yous powerfulness guide hold seen inwards C in addition to C++, they are simply a handgrip to object thence that yous tin access them in addition to brand about 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 agency for reference type object is non copied only the handgrip is copied, i.e. the object is shared betwixt ii reference variable, known every bit aliases. An implication of this is modification done past times ane variable volition behave on to other.

int i = 20; int j = i; j++; // volition non behave on i, j volition live 21 but i volition withal 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 cistron 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 run into that modification on ane primitive variable doesn't behave 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 past times value for the reference type, which is non correct, Java is e'er passed past times value, live it references or primitive variables.

Here is a diagram which clearly shows the departure almost how assignment operator industrial plant differently on primitive in addition to reference variable inwards Java :

 There are ii types of variables inwards Java Difference betwixt Primitive in addition to Reference variable inwards 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 agency ii objects which are logically equal e.g. ii String object amongst 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 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 past times equals()"); }  Output : i in addition to j are equal JPY in addition to YEN are equal past times equals()

You tin run into that primitive variable are rightly compared using == operator, but when nosotros compared ii String object amongst same contents i.e. "JPY", they are non equal using == operator, that's why the minute business is non printed, but when I compared them using equals() method, they are considered equal. This agency yous should always usage equals() method to compare reference types.


Passing primitive in addition to reference variable every bit method argument
When yous overstep primitive values to a method the values are passed to the method, but when yous overstep reference variable, only the handgrip is copied. which agency for primitives, changing the formal parameter's value doesn't behave on the actual parameter's value, patch inwards illustration of reference types, changing the formal parameter's handgrip doesn't behave on the actual parameter's address but changing the formal parameter's internal values does behave on actual parameter's object, because they refer to the same object inwards memory. See Core Java Volume 1 tenth Edition past times Cay S. Horstmann to acquire more.

 There are ii types of variables inwards Java Difference betwixt Primitive in addition to Reference variable inwards Java


For those, who are non aware of formal in addition to actual parameters, formal parameters are those, which is listed(along amongst 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 in addition to 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 run into that changing formal parameter's value doesn't behave on actual parameter's value inwards illustration of primitive variable but it does inwards the illustration of the reference variable, but alone if yous alter the land of an object.


Return value of a method
When yous supply primitive types from a method in addition to then the primitive value is returned but when yous supply a reference type, over again alone handgrip to the is returned. This agency a locally created object tin last 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 e'er created inwards heap memory. patch all primitive local variables are destroyed after method finishes execution.


Stack vs Heap
Primitive variables are created inwards the stack patch reference variable is created inwards heap space, which is managed past times Garbage Collector. See the difference betwixt stack in addition to heap retention inwards Java, for to a greater extent than details.


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


That's all almost the difference betwixt primitive in addition to reference variable inwards Java. Always think that primitive variables are past times default initialized to their default value, which is non cypher in addition to they volition non throw NullPointerException, but if yous access an uninitialized reference variable it volition throw NullPointerException.

Primitive variables are too copied when yous assign them to about other primitive variable in addition to alter on ane variable volition non behave on other, but inwards the illustration 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 Federal Reserve notation is that quondam guide hold less retention than later on due to object metadata overhead e.g. retention require belongings object header. An int primitive variable volition e'er guide hold less retention than Integer object for storing same value.

Further Learning
Complete Java Masterclass
answer)
  • Difference betwixt SOAP in addition to REST Web Service inwards Java? (answer)
  • Difference betwixt HashMap, TreeMap in addition to LinkedHashMap inwards Java? (answer)
  • What is the departure betwixt direct, non-direct in addition to mapped buffer inwards Java? (answer)
  • What is the departure betwixt Factory designing in addition to dependency Injection? (answer)
  • How practise yous calculate the departure betwixt ii dates inwards Java? (answer)
  • Difference betwixt Composition in addition to Inheritance inwards OOP? (answer)
  • 10 differences betwixt JavaScript in addition to Java? (answer)
  • Difference betwixt Maven, ANT in addition to Jenkins inwards Java basis (answer)
  • Difference betwixt ArrayList in addition to LinkedList inwards Java? (answer)
  • What is departure betwixt transient in addition to volatile variable inwards Java? (answer)
  • Some telephone substitution departure betwixt Vector in addition to ArrayList inwards Java? (answer)
  • Difference betwixt get() in addition to load() method inwards Hibernate? (answer)
  • Belum ada Komentar untuk "Difference Betwixt Primitive Together With Reference Variable Inward Java"

    Posting Komentar

    Iklan Atas Artikel

    Iklan Tengah Artikel 1

    Iklan Tengah Artikel 2

    Iklan Bawah Artikel