I was reading More Joel on Software when I came across Joel Spolsky saying something about a particular type of programmer knowing the difference between an i
I'll add to the excellent answers given above, and talk about boxing and unboxing, and how this applies to Java (although C# has it too). I'll use just Java terminology because I am more au fait with that.
As the answers mentioned, int
is just a number (called the unboxed type), whereas Integer
is an object (which contains the number, hence a boxed type). In Java terms, that means (apart from not being able to call methods on int
), you cannot store int
or other non-object types in collections (List
, Map
, etc.). In order to store them, you must first box them up in its corresponding boxed type.
Java 5 onwards have something called auto-boxing and auto-unboxing which allow the boxing/unboxing to be done behind the scenes. Compare and contrast: Java 5 version:
Deque queue;
void add(int n) {
queue.add(n);
}
int remove() {
return queue.remove();
}
Java 1.4 or earlier (no generics either):
Deque queue;
void add(int n) {
queue.add(Integer.valueOf(n));
}
int remove() {
return ((Integer) queue.remove()).intValue();
}
It must be noted that despite the brevity in the Java 5 version, both versions generate identical bytecode. Thus, although auto-boxing and auto-unboxing are very convenient because you write less code, these operations do happens behind the scenes, with the same runtime costs, so you still have to be aware of their existence.
Hope this helps!