Difference Betwixt Primitive As Well As Reference Variable Inwards Java

There are 2 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 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 inwards heap memory. The primary deviation betwixt primitive in addition to reference type is that primitive type ever has a value, it tin never live null but reference type tin live null, which denotes the absence of value. So if y'all practise a primitive variable of type int in addition to forget to initialize it 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 endeavor to access whatever acre or invoke a method on a nix reference, y'all volition live greeted amongst NullPointerException inwards Java. It's rattling of import for every Java developer to empathize difference betwixt primitive in addition to reference variable inwards 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. nix pointer exception.

In short, the primary deviation betwixt 2 types is that primitive types shop actual values but reference type stores handgrip to object inwards the heap. Head First Java 2d Edition too explains this fundamental concept clearly, So y'all tin too receive got a expect at that topographic point to empathize it fleck more.

 There are 2 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 piece of job of both types of variable, its fourth dimension to receive got a deep dive into unopen to to a greater extent than differences betwixt primitive in addition to reference variables inwards Java.



Default value in addition to Null
First deviation betwixt primitive in addition to reference type is that former tin never live null if no value is assigned they receive got 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 2 types of variables inwards Java Difference betwixt Primitive in addition to Reference variable inwards Java


What practise they store?
The minute deviation 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 mightiness receive got seen inwards C in addition to C++, they are simply a handgrip to object thence that y'all tin access them in addition to brand unopen to 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 handgrip is copied. which agency 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 alteration done yesteryear i variable volition behavior on to other.

int i = 20; int j = i; j++; // volition non behavior on i, j volition live 21 but i volition nonetheless live 20  System.out.printf("value of i in addition to j after alteration 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 portion 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 alteration list: %s, copy: %s %n", list, copy);  Output : value of i in addition to j after alteration i: 20, j: 21  value of listing in addition to re-create after alteration list: [EUR], copy: [EUR]

You tin come across that alteration on i primitive variable doesn't behavior 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 deviation virtually how assignment operator plant differently on primitive in addition to reference variable inwards Java :

 There are 2 types of variables inwards Java Difference betwixt Primitive in addition to 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 amongst 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 come across that primitive variable are rightly compared using == operator, but when nosotros compared 2 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 y'all should always usage equals() method to compare reference types.


Passing primitive in addition to reference variable equally method argument
When y'all move yesteryear primitive values to a method the values are passed to the method, but when y'all move yesteryear reference variable, only the handgrip is copied. which agency for primitives, changing the formal parameter's value doesn't behavior on the actual parameter's value, piece inwards illustration of reference types, changing the formal parameter's handgrip doesn't behavior on the actual parameter's address but changing the formal parameter's internal values does behavior 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 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 announcement 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 deviation 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 come across that changing formal parameter's value doesn't behavior on actual parameter's value inwards illustration of primitive variable but it does inwards the illustration of the reference variable, but solely if y'all alter the land of an object.


Return value of a method
When y'all furnish primitive types from a method thence the primitive value is returned but when y'all furnish a reference type, i time again solely handgrip to the is returned. This agency a locally created object tin live 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 in addition to heap retention inwards Java, for to a greater extent than details.


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


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

Primitive variables are too copied when y'all assign them to unopen to other primitive variable in addition to alter on i variable volition non behavior 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 fundamental deviation betwixt primitive in addition to reference variable to banking enterprise complaint is that sometime receive got less retention than subsequently due to object metadata overhead e.g. retention require asset object header. An int primitive variable volition ever receive got 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 deviation betwixt direct, non-direct in addition to mapped buffer inwards Java? (answer)
  • What is the deviation betwixt Factory pattern in addition to dependency Injection? (answer)
  • How practise y'all calculate the deviation betwixt 2 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 deviation betwixt transient in addition to volatile variable inwards Java? (answer)
  • Some fundamental deviation betwixt Vector in addition to ArrayList inwards Java? (answer)
  • Difference betwixt get() in addition to load() method inwards Hibernate? (answer)
  • Komentar

    Postingan populer dari blog ini

    Common Multi-Threading Mistakes Inwards Coffee - Calling Run() Instead Of Start()

    3 Examples Of Parsing Html File Inwards Coffee Using Jsoup

    Why You Lot Should Command Visibility Of Shape Too Interface Inward Java