views:

52

answers:

2

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.

+3  A: 

Everything in Java not explicitly set to something, is initialized to a zero value.

  • For references (anything that holds an object) that is null.
  • For int/short/byte that is a 0.
  • For float/double that is a 0.0
  • For booleans that is a false.

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.

Thorbjørn Ravn Andersen
So how would that go for Strings? null?
Hristo
Yes, unless explicitly assigned, a String variable is null.
Thorbjørn Ravn Andersen
@Hristo, for strings it would be `null`.
jjnguy
@Thor... Thanks! That is awesome. Thanks for the clarification :)
Hristo
Everything but local variables. You need to explicitly initialize any local variables.
Samit G.
@samG... what do you mean?
Hristo
@samG, this is true for all variables. Feel free to check the language spec.
Thorbjørn Ravn Andersen
@Thorbjorn - Local variables must be explicitly initialized. Java will not initialize them for you.`A local variable must be explicitly given a value before it is used, by either initialization or assignment, in a way that can be verified by the compiler using the rules for definite assignment.`JLS - http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.12.5
Samit G.
Local variables are still initially assigned to null. The additional restriction is enforced by the compiler.
Thorbjørn Ravn Andersen
+4  A: 

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):
      o For type byte, the default value is zero, that is, the value of (byte)0.
      o For type short, the default value is zero, that is, the value of (short)0.
      o For type int, the default value is zero, that is, 0.
      o For type long, the default value is zero, that is, 0L.
      o For type float, the default value is positive zero, that is, 0.0f.
      o For type double, the default value is positive zero, that is, 0.0d.
      o For type char, the default value is the null character, that is, '\u0000'.
      o For type boolean, the default value is false.
      o For all reference types (§4.3), the default value is null.
Dave Costa
@Dave... Thanks!
Hristo