In general, the heap memory used by a Java object in Hotspot consists of:
- an object header, consisting of a few bytes of "housekeeping" information;
- memory for primitive fields, according to their size (int n->32 bits)
- memory for reference fields (4 bytes each) (Integer n ->32 bits)
- padding: potentially a few "wasted" unused bytes after the object data, to make every object start at an address that is a convenient multiple of bytes and reduce the number of bits required to represent a pointer to an object.
as per the suggestion of Mark Peters I would like add the link below
http://www.javamex.com/tutorials/memory/object_memory_usage.shtml
int
is a primitive type. Variables of type int
store the actual binary value for the integer you want to represent. int.parseInt("1")
doesn't make sense because int
is not a class and therefore doesn't have any methods.
Integer
is a class, no different from any other in the Java language. Variables of type Integer
store references to Integer
objects, just as with any other reference (object) type. Integer.parseInt("1")
is a call to the static method parseInt
from class Integer
(note that this method actually returns an int
and not an Integer
).
To be more specific, Integer
is a class with a single field of type int
. This class is used where you need an int
to be treated like any other object, such as in generic types or situations where you need nullability.
Note that every primitive type in Java has an equivalent wrapper class:
byte
has Byte
short
has Short
int
has Integer
long
has Long
boolean
has Boolean
char
has Character
float
has Float
double
has Double
Wrapper classes inherit from Object class, and primitive don't. So it can be used in collections with Object reference or with Generics.
Since java 5 we have autoboxing, and the conversion between primitive and wrapper class is done automatically. Beware, however, as this can introduce subtle bugs and performance problems; being explicit about conversions never hurts.
Best Answer
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.