user1296058
user1296058

Reputation: 173

In an array, are the elements stored Primitives or Objects?

int[] array = new int[10];
for (int i = 0; i < array.length; i++) {
    array[i] = 0;
}

in this example, is the value 0 stored inside the array as a primitive or as an object?

Many thanks

Upvotes: 2

Views: 146

Answers (2)

NPE
NPE

Reputation: 500307

In Java, there are both arrays of primitives, and arrays of objects.

int[] is an array of primitives, so 0 is stored as a primitive.

The corresponding array of objects would be of type Integer[]. Storing 0 in such an array would result in it being "auto-boxed" into an Integer object.

It is worth pointing out that Java containers (and any other generic classes) can only work with objects. For example, it is impossible to construct a List of int, only a List of Integer. As I've explained above, this restriction does not apply to arrays.

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726539

In this case, the value is stored as a primitive. If you changed the type to a primitive's wrapper Integer, the value would go in as an "auto-boxed" Object then. For example, this code would autobox your values:

Integer[] array = new Integer[10];
for (int i = 0; i < array.length; i++) {
    array[i] = 0;
}

Upvotes: 5

Related Questions