int vs Integer

Newbies are often confused by the difference between int and Integerboolean vs Boolean,char vs Charactershort vs Shortlong vs Longfloat vs Float or double vsDouble.


An int is a primitive. It is not an Object. An int is a high performance, streamlined beast for calculating numbers in the range -2,147,483,648 [-231] aka Integer.MIN_VALUE to +2,147,483,647 [2 31-1] aka Integer.MAX_VALUE. An int is a bare bones 32-bit chunk of information. int variables are mutable. Unless you mark them final, you can change their value at any time.

An Integer, is a Object that contains a single int field. An Integer is much bulkier than anint. It is sort like a Fedex box to contain the intIntegers are immutable. If you want to affect the value of a Integer variable, the only way is to create a new Integer object and discard the old one.


Fortunately it is easy to convert back and forth between int and Integer.

// to int i from Integer ii
int i = ii.intValue();

// to Integer ii from int i
Integer ii = new Integer( i );


Why Both?

Why are there both int and Integer? For speed. ints, without any Object packaging are compact and fast. Would it not have been easier if there were only one of sort of creature that could do everything and have the compiler automatically figure out when the packaging was needed and when not? The Eiffel language designers thought so, and the Java designers are gradually coming around to the same conclusion.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s