Java Primitive Types: int vs. Integer

Viewed 15470

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.

6 Answers

In Java, int is a primitive data type, while Integer is a Wrapper class.

int, being a primitive data type has 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 integer data. Integer is a class and thus it can call various in-built methods defined in the class. Variables of type Integer store references to Integer objects, just as with any other reference (object) type.

You can find a more detailed explanation here.

Related