Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer.class vs int.class

What is the difference between Integer.class, Integer.TYPE and int.class?

acc to me

  1. Integer.class is a reference of Integer (Wrapper) Class object
  2. but what is then int.class as int is not a class, it's a primitive type. And what does Integer.TYPE refer to?
like image 564
user3380123 Avatar asked Mar 18 '14 05:03

user3380123


People also ask

What is difference between int and Integer?

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.

What is the difference between int [] and Integer []?

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.

Is int and Integer same in Java?

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.

What is the Integer class?

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 .


1 Answers

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 
like image 158
yshavit Avatar answered Sep 22 '22 10:09

yshavit