Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Primitive Types: int vs. Integer

I am confused about when to use primitive vs. non-primitive(?) types (i.e. int vs. Integer) in Java. I realize that in some places you can't use primitive types (for example when making use of generics). But what about in "normal" code? Is there a performance penalty for using non-primitive types? What about when working with Android?

***My question is very similar to this question, which was discovered by one of the posters below. The answers to the linked question give additional insights into this question, which are not covered below.

*** "non-primitive" types are officially referred to as reference types.

like image 347
tjb Avatar asked Jun 24 '11 22:06

tjb


People also ask

What is difference between primitive int and integer 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 difference between int [] A and int a [] in Java?

What is the difference between int[] a and int a[] in Java? There is no difference in these two types of array declaration. There is no such difference in between these two types of array declaration. It's just what you prefer to use, both are integer type arrays.

Is int faster than integer?

Use int when possible, and use Integer when needed. Since int is a primitive, it will be faster.


1 Answers

Short answer: An int is a number; an Integer is a pointer that can reference an object that contains a number. Using Integer for arithmetic involves more CPU cycles and consumes more memory. An int is not an object and cannot passed to any method that requires objects (just like what you said about Generics).

like image 83
eggie5 Avatar answered Oct 10 '22 19:10

eggie5