Kidades
Kidades

Reputation: 670

Why does "variable might not have been initialized" prevent compile?

myObj a;
int b = 1;
int c = 1;

if(b == c) {
    a = new myObj(5);
    b = 2;
}

if(a.getValue() == 5) {
    ....
}

Even though a will always have been initialized when it reaches the second if statement, I will still be unable to compile the program unless I declare it at start.

Also, if I put myObj a = null, it will work, which is basically the same as if I just left it as myObj, but not give an error or prevent compile.

Why is "variable might not have been initialized" an error that prevents compile, instead of just a warning? What is the difference between myObj a; and myObj a = null;?

Upvotes: 1

Views: 94

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

Why is "variable might not have been initialized" an error that prevents compile, instead of just a warning?

Because warnings tend to be ignored, and Java designers knew it. This is a relatively easy catch with a trivial fix, so the cost of erroring out is zero.

What is the difference between "myObj a;" and "myObj a = null;"?

The second declaration says "I thought about the initial value, and it's going to be null."

The first declaration says "I have not made up my mind about the initial value yet; maybe later."

Your case is interesting, because the value is always going to be set, it's just that the compiler is not smart enough to see it.

Upvotes: 3

Related Questions