169

So I'm declaring and initializing an int array:

static final int UN = 0;
int[] arr = new int[size];
for (int i = 0; i < size; i++) {
    arr[i] = UN;
}

Say I do this instead...

int[] arr = new int[5];
System.out.println(arr[0]);

... 0 will print to standard out. Also, if I do this:

static final int UN = 0;
int[] arr = new int[5];
System.out.println(arr[0]==UN);

... true will print to standard out. So how is Java initializing my array by default? Is it safe to assume that the default initialization is setting the array indices to 0 which would mean I don't have to loop through the array and initialize it?

Thanks.

Hristo
  • 45,559
  • 65
  • 163
  • 230

8 Answers8

321

Everything in a Java program not explicitly set to something by the programmer, is initialized to a zero value.

  • For references (anything that holds an object) that is null.
  • For int/short/byte/long that is a 0.
  • For float/double that is a 0.0
  • For booleans that is a false.
  • For char that is the null character '\u0000' (whose decimal equivalent is 0).

When you create an array of something, all entries are also zeroed. So your array contains five zeros right after it is created by new.

Note (based on comments): The Java Virtual Machine is not required to zero out the underlying memory when allocating local variables (this allows efficient stack operations if needed) so to avoid random values the Java Language Specification requires local variables to be initialized.

Thorbjørn Ravn Andersen
  • 73,784
  • 33
  • 194
  • 347
69

From the Java Language Specification:

  • Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10):
 - For type byte, the default value is zero, that is, the value of `(byte)0`.
 - For type short, the default value is zero, that is, the value of `(short)0`.
 - For type int, the default value is zero, that is, `0`.
 - For type long, the default value is zero, that is, `0L`.
 - For type float, the default value is positive zero, that is, `0.0f`.
 - For type double, the default value is positive zero, that is, `0.0d`.
 - For type char, the default value is the null character, that is, `'\u0000'`.
 - For type boolean, the default value is `false`.
 - For all reference types (§4.3), the default value is `null`.
Thorbjørn Ravn Andersen
  • 73,784
  • 33
  • 194
  • 347
Dave Costa
  • 47,262
  • 8
  • 56
  • 72
23

JLS clearly says

An array initializer creates an array and provides initial values for all its components.

and this is irrespective of whether the array is an instance variable or local variable or class variable.

Default values for primitive types : docs

For objects default values is null.

Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
3

According to java,

Data Type - Default values

byte - 0

short - 0

int - 0

long - 0L

float - 0.0f

double - 0.0d

char - '\u0000'

String (or any object) - null

boolean - false

  • 2
    He isn't asking about fields, he is asking about array components. – user207421 Jan 21 '14 at 06:42
  • 3
    @EJP can u please elaborate what is mean of array component???? generally array have some data type(same type) which is initialized as above so can u please tell me, mean of component ??? – Abhishek Singh Jan 28 '14 at 10:37
  • @AbhishekSingh According to [Chapter 10. Arrays](https://docs.oracle.com/javase/specs/jls/se8/html/jls-10.html), a *component* is another name for an *element*: `[...]These variables are called the components of the array.[...]` – rosshjb Dec 01 '21 at 13:15
3

Thorbjørn Ravn Andersen answered for most of the data types. Since there was a heated discussion about array,

Quoting from the jls spec http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.12.5 "array component is initialized with a default value when it is created"

I think irrespective of whether array is local or instance or class variable it will with default values

nantitv
  • 3,539
  • 4
  • 38
  • 61
2

Every class in Java have a constructor ( a constructor is a method which is called when a new object is created, which initializes the fields of the class variables ). So when you are creating an instance of the class, constructor method is called while creating the object and all the data values are initialized at that time.

For object of integer array type all values in the array are initialized to 0(zero) in the constructor method. Similarly for object of boolean array, all values are initialized to false.

So Java is initializing the array by running its constructor method while creating the object

B. Go
  • 1,436
  • 4
  • 15
  • 22
kkk
  • 1,850
  • 1
  • 25
  • 45
  • I do not think this is correct. The jvm zeros out the underlying memory before allocation so the constructor doesn’t have to do anything. You can verify this in a debugger – Thorbjørn Ravn Andersen May 31 '23 at 04:20
1

Java says that the default length of a JAVA array at the time of initialization will be 10.

private static final int DEFAULT_CAPACITY = 10;

But the size() method returns the number of inserted elements in the array, and since at the time of initialization, if you have not inserted any element in the array, it will return zero.

private int size;

public boolean add(E e) {
    ensureCapacityInternal(size + 1);  // Increments modCount!!
    elementData[size++] = e;
    return true;
}

public void add(int index, E element) {
    rangeCheckForAdd(index);
    ensureCapacityInternal(size + 1);  // Increments modCount!!
    System.arraycopy(elementData, index, elementData, index + 1,size - index);
    elementData[index] = element;
    size++;
}
tbraun89
  • 2,246
  • 3
  • 25
  • 44
0

If you want to initialize the array to different value you can use the Arrays.fill() method. This method will help you to set the value for every elements of the array.

import java.util.Arrays;

public class ArraysFillExample {
    public static void main(String[] args) {
        // Assign -1 to each elements of numbers array
        int[] numbers = new int[5];
        Arrays.fill(numbers, -1);
        System.out.println("Numbers: " + Arrays.toString(numbers));

        // Assign 1.0f to each elements of prices array
        float[] prices = new float[5];
        Arrays.fill(prices, 1.0f);
        System.out.println("Prices : " + Arrays.toString(prices));

        // Assign empty string to each elements of words array
        String[] words = new String[5];
        Arrays.fill(words, "");
        System.out.println("Words  : " + Arrays.toString(words));

        // Assign 9 to each elements of the multi array
        int[][] multi = new int[3][3];
        for (int[] array : multi) {
            Arrays.fill(array, 9);
        }
        System.out.println("Multi  : " + Arrays.deepToString(multi));
    }
}

The output of the code snippet above are:

Numbers: [-1, -1, -1, -1, -1]
Prices : [1.0, 1.0, 1.0, 1.0, 1.0]
Words  : [, , , , ]
Multi  : [[9, 9, 9], [9, 9, 9], [9, 9, 9]]

ref: https://kodejava.org/how-do-i-fill-array-with-non-default-value/

Zgpeace
  • 3,927
  • 33
  • 31