Dennis
Dennis

Reputation: 3596

Java: Confused about the variable initialization concept

I'm new to Java and I'm having a bit of trouble understanding the concept of the declaration and the initialization of variables.

For example, when I do:

public class Foo {
    public static void main (String[] args) {
        int x, y;
        for (x = 0 ; x < 10 ; x++) {
           y = x + 1;
        }
        System.out.println(x);
        System.out.println(y);
    }
}

It does not compile and says that "variable y might not have been initialized." However, it does not have any trouble if I tell it to just print out the x value after the loop. Of course it would work if I simply declared it in the beginning (saying int y = 0; or something like that), but I wanted to know why x is printed but not y.

Thanks in advance!


Edit:

I understand that the compiler doesn't actually check inside the loop to see if the variable would be initialized or not so it just says it might not have been initialized, but then why does the following code work? Does the compiler check the if loop but not the for loop?

public class Foo {
    public static void main (String[] args) {
        int x = 0, y;
        if (x == 0) {
            y = 1;
        }
        else {
            y = 2;
        }
        System.out.println(y);
    }
}

Edit 2:

It looks like it gives me the same error if I actually give another condition for the else part so that it would be:

if (x == 0) {
    y = 1;
}
else if (x == 1) {
    y = 2;
}

So I guess the other example worked since y was initialized in both the if and the else part, which means the y would always be initialized no matter what the condition given is. Now I really get it. Thank you!!

Upvotes: 2

Views: 951

Answers (7)

pravin
pravin

Reputation: 501

It depends on two things:

  • executes no matter what (here "x")
  • executes based on some constraint (here "y")

The compiler repels ambiguity in any case so it throws error on witnessing a variable initialization in a block which is conditionally executed.

Upvotes: 0

Dan Rosenstark
Dan Rosenstark

Reputation: 69787

It cannot be determined until run-time whether the for loop will be run even once. Therefore that initialization doesn't count (i.e., the compiler cannot depend on it, so it errors).

It cannot be determined until run-time which of the two -- the if or the else clause -- will fire. However, at compile-time we know that one OR the other will fire, so if you initialize in both, the compilation error goes away.

Upvotes: 1

Wyzard
Wyzard

Reputation: 34571

Consider what could happen if your loop was

for (x = 0 ; x < someOtherVariable ; x++) {

and the value of someOtherVariable happened to be zero. The loop wouldn't run at all, so y would never be initialized.

Of course, the loop you wrote will always run ten times since the lower and upper bound are both hard-coded, but the compiler (apparently) doesn't analyze the code enough to prove that. It sees a variable that's only initialized within a loop, and following the general rule that a loop might not run at all, it complains that the variable might not be initialized.

BTW, int = x, y; isn't valid Java syntax: the equals sign doesn't belong there.

Upvotes: 0

Naved
Naved

Reputation: 4128

If you look in your code; you have initialized x to 0 in for loop and then incrementing it with x++. But you are initializing Y inside loop which may or may not execute at runtime (nothing to do with compile time). In Java, you have to initialize local variable before using it and if you are not doing so compiler will prompt the error. And that is why x is printed and not Y

Upvotes: 1

wintersolutions
wintersolutions

Reputation: 5293

x gets initialized in the for loop (first argument)

Upvotes: 0

paulsm4
paulsm4

Reputation: 121809

This is wrong:

   public class Foo {
        public static void main (String[] args) {
            int = x, y; // Wrong
            for (x = 0 ; x < 10 ; x++) {
               y = x + 1;
            }
            System.out.println(x);
            System.out.println(y);
        }
    }

This is correct:

public class Foo {
    public static void main (String[] args) {
        int x, y; // Declaration only: x and y are uninitialized

This is also correct:

public class Foo {
    public static void main (String[] args) {
        int x = 1, y = 10; // Declaration + initialization

'Hope that helps...

Upvotes: 1

Bozho
Bozho

Reputation: 597344

local variables don't have a default value and you need to initialize them. You are certainly setting the value of x (x=0), but the compiler doesn't check if the loop body will be actually entered. So give y a value of 0.

Upvotes: 9

Related Questions