user133466
user133466

Reputation: 3415

How come Java initializes variables for you?

public class test {
    public static void main(String[] args) {
        int MAX = 5;
        boolean bit[] = new boolean[MAX];
        float[] value = new float[2*3];
        int[] number = {10, 9, 8, 7, 6};
        System.out.println(bit[0]); // prints “false”
        System.out.println(value[3]);   // prints “0.0”
        System.out.println(number[1]);  // prints “9”
        }
    }

I'm testing out the above code, how come Java would initialize the values for you? I thought it should throw compilation error if I don't initialize my variables. Also, what should I do to the line float[] value = new float[2*3]; if I want to initialize them all to 0.0?

Upvotes: 0

Views: 366

Answers (4)

Jon Skeet
Jon Skeet

Reputation: 1503799

Static and instance variables, and elements of arrays are initialized to default values (0, false, '\0', null etc). Local variables aren't initialized by default.

In your code, only the array elements aren't explicitly initialized - the compiler would have a hard time working out whether every array element you tried to use was initialized. What would you expect to happen if the array came from a parameter, for example?

From the Java Language Specification, section 15.10.1:

Then, if a single DimExpr appears, a single-dimensional array is created of the specified length, and each component of the array is initialized to its default value (§4.12.5).

(That's the situation you're in - DimExpr is your 3 * 2 expression here.)

Upvotes: 7

Paul Bellora
Paul Bellora

Reputation: 55233

Elements of an array of a primitive data type are automatically initialized to a default value: 0.0 for float, false for boolean, etc. when the array is not explicitly initialized. In the case of value, the elements of that array should already be initialized to 0.0, since that's the default value.

Upvotes: 0

Desolate Planet
Desolate Planet

Reputation: 561

Your array of floats will implicitly be initialized to 0.0. The compiler will warn you if you attempt to use an uninitialized variable in a method, but object state is always given a default value (unless you choose to override those defaults). You can check what those defaults are against the Java language specification.

Upvotes: 2

John B
John B

Reputation: 32969

Per @Kublai, and since the default value for floats is 0.0 your entire float[] is already being initialized to 0.0 for you. You don't have to do anything else. That is why it printed 0.0 for value[3].

Upvotes: 0

Related Questions