Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"variable might not have been initialized" even though I make sure it is

I am having trouble with Javac on compiling this piece of code:

public static int getYear() {
    Console input = System.console();
    Boolean gotYear = false;
    int year;

    String userInput = input.readLine();

    while (!gotYear) {
        try {
            year = Integer.parseInt(userInput);
            gotYear = true;
        } catch (Exception e) {
            System.out.print("Please insert a valid date. ");
            userInput = input.readLine();
        }
    }

    return year;
}

Javac gives me the error on line return year; that "variable 'year' might not have been initialized". But since it's inside a while loop, I know for sure it will have been initialized. I asked my T.A. about this and he was not able to answer me why this happens. His best guess is that Javac is not a very good compiler for figuring this kind of stuff out.

Basically, why is this error happening? I know I can fix it by initializing year before I enter the while loop, but I wanted to know if there is another way of achieving what I'm trying to achieve.

like image 745
raphaelgontijolopes Avatar asked Dec 25 '22 04:12

raphaelgontijolopes


2 Answers

No. You have to initialize. Local aka method variables must gets initialized before they use.

Local variable won't get default values. You have to initialize them, before you use.

like image 30
Suresh Atta Avatar answered Dec 28 '22 06:12

Suresh Atta


Your year variable is initialized in a try block. It's obvious to us that it won't get out the loop until something OK is input. But the compiler's rules are simpler than that : as the initialisation can be disrupted by an exception, it considers that year may be uninitialized.

like image 99
Julien Avatar answered Dec 28 '22 07:12

Julien