0

For some reason even when I initialise the variable outside of the for loop, my code will not compile...

    public static void main(String[] args) {
      int x;

      for (int i = 0; i < 4; i++){
        x = 10;
      }

      System.out.println(x);
    }

I get the error:

    error: variable x might not have been initialized
      System.out.println(x);

any help will be much appreciated as i know the answer is going to be so simple.

Ben Graham
  • 65
  • 5
  • 1
    Possible duplicate of [Variable might not have been initialized error](https://stackoverflow.com/questions/2448843/variable-might-not-have-been-initialized-error) – Madhawa Priyashantha Mar 03 '18 at 12:54

3 Answers3

0

You declared the variable, you did not initialize it and without any optimizations the compiler would not know if your loop ever produced a single iteration to actually initialize it. Try:

public static void main(String[] argv) {
    int x = 0;

    for (int i = 0; i < 4; i++){
        x = 10;
    }

    System.out.println(x);
}

Admittedly, it is quite a silly "feature" of the java compiler.

Oleg Sklyar
  • 9,834
  • 6
  • 39
  • 62
0

simply change it so that int x = 0;

it is inferred that x = 0, but you need to initialise the value in this case.

    public static void main(String[] args) {
    int x = 0;

    for (int i = 0; i < 4; i++){
        x = 10;
    }

    System.out.println(x);
}

EDIT: x value (can't be null)

Connor J
  • 540
  • 1
  • 6
  • 17
0

Primitive variables that you declare at a class level are automatically initialised for you to zero (or false). If your variable is an object it will default to null. If the scope of the variable is at method level, you need to provide a value for it: That is what the compiler is telling you.
In your example the compiler is not clever enough to see that a value will always be assigned to variable x and so demands that you provide an initialisation value.

You just need to add int x = 0; and it will compile.

paulturnip
  • 106
  • 5