Which one to use, int or Integer

JavaDatabasePerformanceTypesPrimitive

Java Problem Overview


I need to create a data transfer object, which I will use for storing the records retrieved from database. In this data transfer object, I need to declare a numeric field. For that which one is better - int or Integer

If I am defining the field as Integer, will there be any performance impact because of 'Integer' type if I am going to retrieve more than 2000 records from DB!?

Thanks in advance.

Java Solutions


Solution 1 - Java

Integer is a better option, as it can handle null; for int, null would become 0, silently, if resultSet.getInt(..) is used. Otherwise, it might throw some exception, something like, "Unable to set null to a primitive property".

Performance is of little concern here.

  • if you choose int, you will end-up adding extra handling code; and that wouldn't benefit you much. Your code will not be clean and straight-forward, lot of boiler-plate code, and you wouldn't even gain performance.
  • let me make it clear, for databases, null is not same as zero. Sometimes you end-up entering 0, where null was intended. Imagine the case where user submitted a form, and doesn't supply any value for int. You will end up getting 0 by default. It makes sense, or does that really, when that field is not null in the database.

Solution 2 - Java

You should really make your decision based on- what you need your object to do, rather than the performance costs. Deciding based on performance should be done, once a speed issue has been identified with a profiler - the root of all evil and all that.

Look at some of the features of both and use that for your decision, e.g.

  • Integer can be null, int cannot. So is the int in the DB a Nullable field?
  • Do you need access to the Integer class methods?
  • Are you doing arithmetic?

Personally, I always opt for the primitive over the wrapper. But that's just a preference thing, rather than based on any technical merit.

Solution 3 - Java

To my mind, the choice between declaring something as int or Integer simply comes down to whether null is a valid value for it or not. Autoboxing (and autounboxing) will take care of any conversion issues where the number simply must be one type or another. Performance (as has been pointed out) is also unlikely to be noticable in almost all cases.

Besides, int should be the natural choice, and is likely to be the most performant should that be an issue anyway. If you need to be able to store nulls, then you have to use Integer (and also ensure that no null references are auto-unboxed for a method that takes simply ints as this will result in a NullPointerException).

Solution 4 - Java

Integer is theoretically slower than int, however the performance impact should be minimal unless you are crunching numbers. Also JIT optimizations will reduce the performance loss.

Use the one that better suits your situation in terms of primitive or reference type.

Solution 5 - Java

int is 10x faster than integer

we test this code with jetm performance library

int n;
EtmPoint point1 = etmMonitor.createPoint("test:objects");
for (n = 0; n < 1000000; n++) {
    Integer t = 0;
    t = 10;
    t = 11;
}

point1.collect();
EtmPoint point = etmMonitor.createPoint("test:primitives");
for (n = 0; n < 1000000; n++) {
    int t = 0;
    t = 10;
    t = 11;
}
point.collect();

etmMonitor.render(new SimpleTextRenderer());

and the results:
test:objects 10.184
test:primitives 1.151

Solution 6 - Java

To give you an idea, 2000 Integer would add about 0.5 ms to you query. If you have to serialize this data it could add quite a bit more.

However, correctness should come first. There is no point being very fast but wrong. You have to consider null values and how you handle them. (Unless the column is NOT NULL) You could use Integer.MIN___VALUE or you could use a long field instead of int and use Long.MIN_VALUE for null. Even though it is larger than int, it would still be many times smaller and more efficient than Integer.

Solution 7 - Java

I guess it depends among other things on what you are using for accessing the database. With plain old JDBC you could do with ints, while an ORM could silently convert them to Integers anyway. And Integer would allow you to handle nulls.

Solution 8 - Java

int is used by java for most all calculations. Integer is used in all forms of Collections except for primitive arrays.

Using lots of temporary Integers with thrash the garbage collector and use unprofilable CPU in the background that will cause general slowdowns in everything. Too many temporaries being trashed per second will cause the CG to enter emergency "I need memory now" mode that can cause stalls in latency critical applications (ie: real time interactive graphics, physical device controllers or communications)

So for me if I have a lot of nested calls that do no math but access a lot of collections such as using keys for maps I use Integer so as to avoid tons of auto boxing when arguments are passed.

If the operations are math intensive or used as loop counters or other math oriented operations and not stored in collections (other than primitive arrays) I use the primitive. The same goes for all the other primitives except String which is a full fledged object.

Solution 9 - Java

int can't be cast to the String with using the toString or (String).

Integer can cast to String with toString or (String) and it can handle null.

Solution 10 - Java

If you want to check for a null value then Integer is best but if you want to compare the integer then int may be better. In the following example I am using integer c= 1000 and d= 1000 and compare it return false but in case of int they will return true.

public class IntegerCompare {

	public static void main(String[] args) {
		int a = 1000;
		int b = 1000;

		Integer c = 1000;
		Integer d = 1000;

		if (a == b) {
			System.out.println("int Value Equals");

		}
		if (c == d) {
			System.out.println("Integer value Equals");

		} else {

			System.out.println("Integer Value Not Equals");
		}
	}
}

Solution 11 - Java

One scenario to cover would be validation.

Imagine we have the following class:

class Foo{
    @Min(value = 10)
    int val;
}

If the user doesn't provide a value for val in the request, we will get a nasty NumberFormatException.

If int is replaced with Integer, we can use @NotNull and resolve this issue more gracefully.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVeeraView Question on Stackoverflow
Solution 1 - JavaAdeel AnsariView Answer on Stackoverflow
Solution 2 - JavatddmonkeyView Answer on Stackoverflow
Solution 3 - JavaAndrzej DoyleView Answer on Stackoverflow
Solution 4 - JavammxView Answer on Stackoverflow
Solution 5 - JavaAmineView Answer on Stackoverflow
Solution 6 - JavaPeter LawreyView Answer on Stackoverflow
Solution 7 - JavaagnulView Answer on Stackoverflow
Solution 8 - JavapeterkView Answer on Stackoverflow
Solution 9 - JavaDeepakView Answer on Stackoverflow
Solution 10 - JavaPankaj SinglaView Answer on Stackoverflow
Solution 11 - JavaRamanlfcView Answer on Stackoverflow