Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Which one is best in programming - int or Integer? Especially whenever both are doing the same task?

I am writing an application in Java. In most of the places of primitive data types, I use int; and for objects, I use Integer. So I am confused- which one is the best in places, where we have to use objects.

According to performance, which one is best for a Java application?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
266 views
Welcome To Ask or Share your Answers For Others

1 Answer

Use int when possible, and use Integer when needed. Since int is a primitive, it will be faster. Modern JVMs know how to optimize Integers using auto-boxing, but if you're writing performance critical code, int is the way to go.

Take a look at this and this article. Although you shouldn't treat them as absolute truths, they do show that objects will be slower than their primitive counterparts.

So, use int whenever possible (I will repeat myself: if you're writing performance critical code). If a method requires an Integer, use that instead.

If you don't care about performance and want to do everything in an object oriented fashion, use Integer.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...