What is the difference between int
and Integer
. Yes, one is primitive
and another one is wrapper
, what is the situation to use them correctly.
Also what is the difference between :
int i=0;
++i
and
i++
What is the difference between int
and Integer
. Yes, one is primitive
and another one is wrapper
, what is the situation to use them correctly.
Also what is the difference between :
int i=0;
++i
and
i++
part 1
One example .. you can use Integer
as the key of HashMap
but you can't use int. Because an Object
is needed.
So where you need an int
value as an object there you need to use Integer
class.
part 2
++i is pre increment i++ is post increment
for example
i = 0;
System.out.println(i++) //will print 0 then the i will be 1.
and
i = 0;
System.out.println(++i) // here i wil be incremented first then print 1.
Integer
is a wrapper class for int
which is a primitive data type. Integer
is used when int
can't suffice. For example: In generics, the type of the generic class, method or variable cannot accept a primitive data type. In that case Integer
comes to rescue.
List<int> list; //Doesn't compiles
List<Integer> list; // Compiles
Moreover Integer
comes with a plethora of static methods, like toBinaryString
, toHexString
, numberOfLeadingZeros
, etc. which can come in very handy.
As already explained above An Integer is an object, whereas an int is a primitive. So you can have a null reference to an Integer and a Set or List of them. You can not do that with an int
I find this null reference very useful, when i have to store int values in database. I can store a null value when I use Integer. But cannot do so when I use int.
An Integer
is an object, whereas an int
is a primitive. So you can have a null reference to an Integer
and a Set
or List
of them. You can not do that with an int
.
A basic explanation is an int
is a primitive data type and literally is only a value stored in memory. An Integer
is a Java object that wraps an int
in a Class with lots of nice/helpful methods that can be called to work with that backing int
hidden inside. This is the same with most of the primitive data types, such as boolean
and Boolean
, char
and Character
, etc. This is refereed to as Boxing
a primitive. Unboxing being the opposite, taking an Object and extracting the backing primative.
Here's an example of how one may use Integer
to convert a String
into an int
(boxed to an Integer
)
String someString = "10";
Integer intObj = Integer.parseInt(someString);
System.out.println(intObj.toString());
You'll find that some of the data types have more helpful methods than others. Check the JavaDoc's for each of the types you are interested in, there are a lot of goodies in there!