Search code examples
javawrapperprimitive

What is the difference in usage of primitive and wrapper data type and what is the need of wrapper data type?


I searched it all over the web, but all the answers just consisted of the difference. I know the difference, but I don't understand the difference in their applications.

For example, suppose we have to take two floating values, if we use double, we can easily compare using a==b, whereas if we use Double, we will have to use a.equals(b).


Solution

  • You can find it on blog

    1. First

    Double is a reference type so you can use it as template argument

    For Example :

    public class Tmp<T> {
        public Tmp() {
        }
    }
    

    If you want to create a class like That.

    Then you have to pass reference type, while creating object of in. For example

    new Tmp<Integer>()
    

    You will get an error if you create object like :

    new Tmp<int>()
    

    2. Second

    Only because of Wrapper classes it is possible to do generic datatype programming.

    For example bellow method accept any kind of number (Byte, Integer, Double, Short, Float, Long, BigDecimal, BigInteger, AtomicInteger, AtomicLong) and return the Integer addition of that numbers.

    public Integer add(Number a, Number b){
        return a.intValue() + b.intValue();
    }
    

    3. Third

    In earlier version of Java is not supporting AutoBoxing and AutoUnboxing. So, if You use that version of Java then you can easily differentiate the both.

    For example if you use Java 1.4 or earlier version then:

    Integer a = 1; // Auto Boxing(Not Works)
    Integer a2 = new Integer(2); // Boxing (It Works)
    

    4. Fourth

    The Storage of both also differ Primitive types are stored in Stack while reference types are store in Heap

    5. Fifth

    You can use functionality of that class like parsing string to Integer, Double, etc and use consents of the same.

    Here are the functions and consents of Integer class

    enter image description here

    6. Sixth

    You can serialize Integer while it is not possible with int

    7. Seventh

    You can pass Integer as a RMI method but the same is not possible with int

    Note : Both Integer and int can be part of another object in RMI argument in fact inside the Integer class they store value in int.

    8. Eighth

    Variable of int is mutable (It is not the case with final int) while Integer is immutable. It will create new object when we change the value.