Possible Duplicate:
Why can Integer and int be used interchangably?
I am trying to understand the difference between these. Can I declare something to be an int for example and then compare this with a number that I put in an Integer? Also why does Java have the two. Why not just combine these?
Can someone help me by showing me a 3-4 line code example of how each is used?
In Java, int is a primitive data type while Integer is a Wrapper class. int, being a primitive data type has got less flexibility. We can only store the binary value of an integer in it. Since Integer is a wrapper class for int data type, it gives us more flexibility in storing, converting and manipulating an int data.
The major difference between an Integer and an int is that Integer is a wrapper class whereas int is a primitive data type. An int is a data type that stores 32-bit signed two's complement integer whereas an Integer is a class that wraps a primitive type int in an object.
From "Primitive Data Types": "Primitive types are special data types built into the language; they are not objects created from a class." That, in turn, means that no, int doesn't inherit from java.
Use int when possible, and use Integer when needed. Since int is a primitive, it will be faster.
int
primitive is not an object. Arrays allow primiteves:
int[] array = new int[10];
but generics don't:
List<int> //won't compile
This is the primary reason to use wrapper classes these days. Also you can use Integer
where Object
is expected. Finally Integer
can have null
value if you want to implement optionality.
Note that there are some languages that dealt with that inconsistency. In c# you have value types, in scala Int
class extend from AnyVal
class while normal objects extend AnyRef
(both of these extend from Any
).
See boxing of types in Java. There is talk of making them exactly the same starting with Java 9.
int
type and Integer class are different types. You can't compare directly a primitive int
with a Integer
object. You need to get intValue
from the Integer
object. int
with them. So you will need a Integer
wrapper.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With