What is the difference between Integer.class
, Integer.TYPE
and int.class
?
acc to me
Integer.class
is a reference of Integer (Wrapper) Class objectint.class
as int
is not a class, it's a primitive type. And what does Integer.TYPE
refer to?A int is a data type that stores 32 bit signed two's compliment integer. On other hand Integer is a wrapper class which wraps a primitive type int into an object. int helps in storing integer value into memory. Integer helps in converting int into object and to convert an object into int as per requirement.
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.
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 Integer class wraps a value of the primitive type int in an object. An object of type Integer contains a single field whose type is int .
Integer.class
is, as you say, a reference to the Class
object for the Integer
type.
int.class
is, similarity, a reference to the Class
object for the int
type. You're right that this doesn't sound right; the primitives all have a Class
object as a special case. It's useful for reflection, if you want to tell the difference between foo(Integer value)
and foo(int value)
.
Integer.TYPE
(not Integer.type
, mind you) is just a shortcut for int.class
.
You can get a sense of this with a simple program:
public class IntClasses { public static void main(String[] args) { Class<Integer> a = int.class; Class<Integer> b = Integer.TYPE; Class<Integer> c = Integer.class; System.out.println(System.identityHashCode(a)); System.out.println(System.identityHashCode(b)); System.out.println(System.identityHashCode(c)); } }
Example output (it'll be different each time, but the first two will always be the same, and the third will virtually always be different):
366712642 366712642 1829164700
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