2

The following code doesn't pass compilation. It is giving me this error:

variable h might not have been initialized

public class MnmEx {

    public static void main(String[] args) {
        
        int h; 
        for (int i = 0; i < 50; i++) {
            for (int j = 0; j < 50; j++) {
                if (j == 10) {
                    h = 20; 
                }
            }
        }
        System.out.println(h); 
    }
}
Eran
  • 387,369
  • 54
  • 702
  • 768
Yosef-S
  • 29
  • 1

1 Answers1

3

The compiler doesn't analyze your for loops to make sure that h is always assigned within them. Therefore it doesn't know if at the point where you attempt to print h (System.out.println(h)), it has already been assigned.

This can be easily avoided by giving h an initial value:

int h = 0;
Eran
  • 387,369
  • 54
  • 702
  • 768