For example why can you do:
int n = 9;
But not:
Integer n = 9;
And you can do:
Integer.parseInt("1");
But not:
int.parseInt("1");
For example why can you do:
int n = 9;
But not:
Integer n = 9;
And you can do:
Integer.parseInt("1");
But not:
int.parseInt("1");
To optimize the Java code runtime,
int
primitive type(s) has been added includingfloat
,bool
etc. but they come along with there wrapper classes so that if needed you can convert and use them as standard Java object along with many utility that comes as their member functions (such asInteger.parseInt("1")
).int
is a primitive data type whileInteger
is a Reference or Wrapper Type (Class) in Java.after
java 1.5
which introduce the concept of autoboxing and unboxing you can initialize bothint
orInteger
like this.Integer
is a Class defined injdk
library andparseInt()
is a static method belongs toInteger
ClassSo,
Integer.parseInt("1");
is possible in java. butint
is primitive type (assume like a keyword) in java. So, you can't callparseInt()
withint
.int is a primitive type and not an object. That means that there are no methods associated with it. Integer is an object with methods (such as parseInt).
With newer java there is functionality for auto boxing (and unboxing). That means that the compiler will insert Integer.valueOf(int) or integer.intValue() where needed. That means that it is actually possible to write
which is interpreted as
An int variable holds a 32 bit signed integer value. An Integer (with capital I) holds a reference to an object of (class) type Integer, or to null.
Java automatically casts between the two; from Integer to int whenever the Integer object occurs as an argument to an int operator or is assigned to an int variable, or an int value is assigned to an Integer variable. This casting is called boxing/unboxing.
If an Integer variable referencing null is unboxed, explicitly or implicitly, a NullPointerException is thrown.
(In the above text, the term "variable" means local variable, field or parameter)
This is taken from Java: The Complete Reference, Ninth Edition
int
is a primitive type that represent an integer. whereasInteger
is an Object that wrapsint
. TheInteger
object gives you more functionality, such as converting to hex, string, etc.You can also use OOP concepts with
Integer
. For example, you can use Integer for generics (i.e.Collection
).<Integer>