Ronald Daniel is a software developer, specializing in J2EE Programming technologies and frameworks. Has been in the IT World since 2008, still much to learn yet. Been a trainer for a while, specializing in training subjects: Java, J2EE, Sql-ing in Oracle, Sql Server and MySQL. Has been involved in numerous IT Software Development Projects and still wants to be better than yesterday. Feel free to drop email to rd.djunaedi@gmail.com Ronald is a DZone MVB and is not an employee of DZone and has posted 5 posts at DZone. You can read more from them at their website. View Full User Profile

Don't Compute With Wrapper

04.05.2013
| 2423 views |
  • submit to reddit

As a Java Developer, i got these interview questions a lot… really. What is the difference between int and Integer, which one is better ?

The answer for the difference, can be answered easily, int is a primitive data type and Integer is wrapper object for int, and so on bla bla bla google it.

But, for the better one the answer would be  depends on the purpose of it. For this example, i will put simple demo to show how slow is the Wrapper when we use it for the mathematics computation.

import java.util.Date;
public class Tester {
    public void runInteger() {
        long startTime = new Date().getTime();
        Integer ctr = 0;
        for (int i = 0; i < Integer.MAX_VALUE; i++) {
            ctr += i;
        }
        long endtime = new Date().getTime();
        System.out
                .println("Time for Integer: " + (endtime - startTime) + " ms");
 
        System.out.println();
    }
 
    public void runint() {
        long startTime = new Date().getTime();
 
        int i = 0;
        int ctr = 0;
        for (i = 0; i < Integer.MAX_VALUE; i++) {
            ctr += i;
        }
 
        long endtime = new Date().getTime();
 
        System.out.println("Time for int: " + (endtime - startTime) + " ms");
 
        System.out.println();
    }
 
    public static void main(String[] args) {
        new Tester().runInteger();
        new Tester().runint();
        new Tester().runInteger();
    }
}

and the output was:

    Time for Integer: 7652 ms

    Time for int: 5 ms

    Time for Integer: 7541 ms

We can see the interval difference between primitive and wrapper on this example is quite huge ~ 7500ms .  But, unfortunately, many developers today didnt and dont aware of this,  because of the auto boxing-unboxing features since Java 1.5, the process is hidden on the background.


 

Published at DZone with permission of Ronald Daniel, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)