Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why program is not allowing to initialize the static final variable?

Tags:

java

static

final

I came across the Java code below which looks good at first but never compiles :

public class UnwelcomeGuest {

    public static final long GUEST_USER_ID = -1;
    private static final long USER_ID;

    static {
        try {
            USER_ID = getUserIdFromEnvironment();
        } catch (IdUnavailableException e) {
            USER_ID = GUEST_USER_ID;
            System.out.println("Logging in as guest");
        }
    }

    private static long getUserIdFromEnvironment()
            throws IdUnavailableException {
        throw new IdUnavailableException(); // Simulate an error
    }

    public static void main(String[] args) {
        System.out.println("User ID: " + USER_ID);
    }
}//Class ends here


//User defined Exception
class IdUnavailableException extends Exception {

     IdUnavailableException() { }

}//Class ends here

Below is the error message which comes in the IDE : variable USER_ID might already have been assigned.

Is there any problem with the value assignment to the static final variable ?

like image 736
Kshitij Jain Avatar asked Sep 16 '13 16:09

Kshitij Jain


Video Answer


1 Answers

Final variables allow at most one assignment in the constructor or the initializer block. The reason this does not compile is that Java code analyzer sees two assignments to USER_ID in branches that do not look mutually exclusive to it.

Working around this problem is simple:

static {
    long theId;
    try {
        theId = getUserIdFromEnvironment();
    } catch (IdUnavailableException e) {
        theId = GUEST_USER_ID;
        System.out.println("Logging in as guest");
    }
    USER_ID = theId;
}
like image 167
Sergey Kalinichenko Avatar answered Sep 23 '22 03:09

Sergey Kalinichenko