9

Considering following basics:

  1. Any Object lives only on heap,
  2. Array IS-A Object and
  3. Integer IS-A Object

I find myself difficult to answer such a simple question: Is there any difference between int[] and Integer[] inside of JVM? Or it makes sense only at "compile-time"?

Maroun
  • 87,488
  • 26
  • 172
  • 226
Ilya Gubarev
  • 137
  • 1
  • 1
  • 5

4 Answers4

22

There is a difference at run-time.

int[] is an array of primitive int values. Integer[] is an "object" array, holding references to Integer objects.

Most important practical difference: int[] cannot hold null values.

But I'm still confused: does int[] store just a primitive values? If so - doesn't it mean that primitive types can live on heap without being wrapped?

int[] does store primitive types. And the array itself lives on the heap. However, those primitives are allocated as part of the array. They are not stored separately elsewhere on the heap. This is very similar to how a primitive field is part of an object instance: The object is on the heap, and its field is an integral part of that object (whereas for a non-primitive field, only the reference is stored inside the object and the target instance that reference points at is stored separately on the heap).

You could say the int is "wrapped" inside the array.

Thilo
  • 241,635
  • 91
  • 474
  • 626
  • you can also assign null to array irrespective of the type it stores – Anirudha Sep 17 '13 at 08:55
  • yes, the array itself can be null. But not elements in a primitive type array. – Thilo Sep 17 '13 at 08:57
  • 1
    @Thilo, thank a lot for the answer. But I'm still confused: does int[] store just a primitive values? If so - doesn't it mean that primitive types can live on heap without being wrapped? – Ilya Gubarev Sep 17 '13 at 08:58
7

This image should help you to understand the difference:

enter image description here

int is a number, it's a primitive type.
Integer is an object.

When you have an array of Integers, you actually have an array of objects. Array of ints is an array of primitive types.

Since arrays are objects, they're allocated on the heap. If it's an array of ints, these ints will be allocated on the heap too, within the array.

You may find this link helpful.

Maroun
  • 87,488
  • 26
  • 172
  • 226
1

Firstly, Integer is a class/object while int is a primitive type. Integer is a wrapper for int. If you need a null value to be stored, or need to use collection, use Integer. You can do-

List<Integer> integerList = new ArrayList<Integer>();

So, an array of primitive types are different from an array of integer objects.

Sajal Dutta
  • 7,258
  • 25
  • 33
1
  • Integer[] is an array (object) of objects
  • int[] is an array (object) of primitives

Than there is a difference between Integer and int summarized here.

Community
  • 1
  • 1
Terafor
  • 1,550
  • 16
  • 26