What is the difference between an int and an Integer in Java and C#?

Well, in Java an int is a primitive while an Integer is an Object. Meaning, if you made a new Integer:

Integer i = new Integer(6);

You could call some method on i:

String s = i.toString();//sets s the string representation of i

Whereas with an int:

int i = 6;

You cannot call any methods on it, because it is simply a primitive. So:

String s = i.toString();//will not work!!!

would produce an error, because int is not an object.

int is one of the few primitives in Java (along with char and some others). I'm not 100% sure, but I'm thinking that the Integer object more or less just has an int property and a whole bunch of methods to interact with that property (like the toString() method for example). So Integer is a fancy way to work with an int (Just as perhaps String is a fancy way to work with a group of chars).

I know that Java isn't C, but since I've never programmed in C this is the closest I could come to the answer. Hope this helps!

Integer object javadoc

Integer Ojbect vs. int primitive comparison


In Java, the 'int' type is a primitive, whereas the 'Integer' type is an object.

In C#, the 'int' type is the same as System.Int32 and is a value type (ie more like the java 'int'). An integer (just like any other value types) can be boxed ("wrapped") into an object.


The differences between objects and primitives are somewhat beyond the scope of this question, but to summarize:

Objects provide facilities for polymorphism, are passed by reference (or more accurately have references passed by value), and are allocated from the heap. Conversely, primitives are immutable types that are passed by value and are often allocated from the stack.

Tags:

C#

Java

Integer

Int