Long vs Integer, long vs int, what to use and when?

I know how to tick the V picture I know how to tick the V · May 2, 2011 · Viewed 304.6k times · Source

Sometimes I see API's using long or Long or int or Integer, and I can't figure how the decision is made for that?

When should I choose what?

Answer

Borealid picture Borealid · May 2, 2011

Long is the Object form of long, and Integer is the object form of int.

The long uses 64 bits. The int uses 32 bits, and so can only hold numbers up to ±2 billion (-231 to +231-1).

You should use long and int, except where you need to make use of methods inherited from Object, such as hashcode. Java.util.collections methods usually use the boxed (Object-wrapped) versions, because they need to work for any Object, and a primitive type, like int or long, is not an Object.

Another difference is that long and int are pass-by-value, whereas Long and Integer are pass-by-reference value, like all non-primitive Java types. So if it were possible to modify a Long or Integer (it's not, they're immutable without using JNI code), there would be another reason to use one over the other.

A final difference is that a Long or Integer could be null.