int vs Integer
Â Â Newbies are often confused by the difference between int and Integer.
Â Â To properly understand the difference, you should read an introductory textbook on Java. I will make a small stab at answering here.
Â Â Everything I say here applies analogously to char and Character, short and Short, long and Long, float and Float, double and Double.
Â Â Definitions
Â Â 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 an int. It is sort like a Fedex box to contain the int. Integers 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.
Â Â Which is better?
Â Â That is like asking which is better a volley ball or a volleyball in a Fedex box. It depends what you want to do with it.
Â Â int vs Integer
Â Â ability unboxed
Â Â int boxed
Â Â Integer
Â Â Calculate with it, + - * / % ^ etc.
Â Â Pass it as a parameter
Â Â return it as a value
Â Â Use methods on it from java.lang.Integer
Â Â Store it in a Vector or other Collection
Â Â Use it as a HashMap key
Â Â serialize it
Â Â send it by itself over RMI (Remote Method Invocation)
Â Â send it as part of another Object over RMI
Â Â pass it as a generic object to a TableCellRenderer. You may pass a variety of different types via the same paramter.
Â Â Allow for a null value that means there is no value.
Â Â Converting
Â Â 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 );