Showing posts with label Wrapper Classes. Show all posts
Showing posts with label Wrapper Classes. Show all posts

Friday, August 11, 2017

Why do people still use primitive types in Java?

a)  Avoid creating unnecessary objects. Long took 42 sec where as long took 4 sec to complete calculation.

/* Avoid creating unnecessary objects */
public class WrapperClass {
     public static void main(String[] args) {
          System.out.println(System.currentTimeMillis());
          long sum = 0L; // uses Long, not long
          for (long i = 0; i <= Integer.MAX_VALUE; i++) {
              sum += i;
          }
          System.out.println(sum);
          System.out.println(System.currentTimeMillis());
     }
}

Output

Using Long sum =0L – program took 7 sec whereas using
long sum =0L program took 1 sec to complete

    b) The lack of native value equality is also a concern (.equals() is fairly verbose compared to ==)

      Also result is unpredictable depending on JVM cache implementation.

public class TestInteger {

     public static void main(String[] args) {
          int x=1000;
          int y=1000;
          System.out.println(x==y);
         
          Integer x1 = 1000;
          Integer y1 = 1000;
          System.out.println(x1 == y1);

     }
}

Output
True
False

    c) Assignment work is often confusing taking wrapper and primitive both into account.

    public class TestInteger {

     public static void main(String[] args) {
          Integer i=null;
          int i1=i;

     }
}

Exception in thread "main" java.lang.NullPointerException      at com.wrapper.TestInteger.main(TestInteger.java:7)


     d)    Boxed types have poorer performance and require more memory.


     e)    Primitive types are much faster:

int i;
i++;

Integer (all Numbers and also a String) is an immutable type: once created it can not be changed. If i was Integer, than i++ would create a new Integer object - much more expensive in terms of memory and processor.
Can you really imagine a scenario where Wrapper is used replaced with primitive
  for (Integer i=0; i<10000; i++) {
      do something
  }

loop with java.lang.Integer instead? A java.lang.Integer is immutable, so each increment round the loop would create a new java object on the heap, rather than just increment the int on the stack with a single JVM instruction. The performance would be diabolical.

References

http://www.javaworld.com/article/2150208/java-language/a-case-for-keeping-primitives-in-java.html