1

Can you store int values into a Integer array?

Given an array:

Integer[] array = new Integer[10];

Are the following two statements equivalent?

Integer x = new Integer(1);
array[0] = x;

int x = 1;
array[0] = x;

2 Answers 2

2

They are not 100% equivalent. The following should be equivalent however:

Integer x = Integer.valueOf(1); 
array[0] = x;

int x = 1; 
array[0] = x;

Note that the int primitive gets autoboxed to the Integer wrapper class. So you're not storing an int primitive in the Integer array, but an Integer object.

You should hardly ever use the Integer constructor (which always creates a new object) but use one of its static factory methods or autoboxing (less code), which allow to cache instances (since they are immutable).

Sign up to request clarification or add additional context in comments.

Comments

0

Once the values are inside the array itself, they are both values of type Integer. If you pass a primitive object to an instance of its wrapper class, then that primitive type is autoboxed, meaning its automatically converted to the type of its wrapper class.

Integer x = 4; //autoboxing: "4" is converted to "new Integer(4)"

Likewise, a wrapper class type can is unboxed when it is passed to a primitive type:

int x = new Integer(4); //unboxing: "new Integer(4)" is converted to primitive int 4

For your purposes, both examples your wrote will work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.