Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can Integer and int be used interchangably?

I am confused as to why Integer and int can be used interchangeably in Java even though one is a primitive type and the other is an object?

For example:

Integer b = 42;
int a  = b;

Or

int d = 12;
Integer c = d;
like image 862
Jamal Khan Avatar asked Aug 19 '11 12:08

Jamal Khan


People also ask

Why do we use Integer instead of int?

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.

Which takes more memory int or Integer?

Each Integer object can occupy 4 (or more) times the storage space as a primitive 'int', so if the extra capabilities aren't needed and your Java program must hold many (i.e., thousands or more) integer values in memory, consider using int instead of Integer.

What can I use instead of int?

You can use long, which will give you twice as many bits. If that's not big enough, you can move to BigInteger, which will give you as many as you want, however you won't be able to user operators (like div and mod) directly. Save this answer.

What is the difference between int and long int?

An int is a 32-bit integer; a long is a 64-bit integer. Which one to use depends on how large the numbers are that you expect to work with. int and long are primitive types, while Integer and Long are objects.


1 Answers

The first few sentences of the posted article describe it pretty well:

You can’t put an int (or other primitive value) into a collection. Collections can only hold object references, so you have to box primitive values into the appropriate wrapper class (which is Integer in the case of int). When you take the object out of the collection, you get the Integer that you put in; if you need an int, you must unbox the Integer using the intValue method. All of this boxing and unboxing is a pain, and clutters up your code. The autoboxing and unboxing feature automates the process, eliminating the pain and the clutter.

That is basically it in a nutshell. It allows you take advantage of the Collections Framework for primatives without having to do the work yourself.

The primary disadvantage is that it confuses new programmers, and can lead to messy/confusing code if it's not understood and used correctly.

like image 188
Alan Delimon Avatar answered Oct 05 '22 10:10

Alan Delimon