Reputation: 1793
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 ?
Upvotes: 9
Views: 237
Reputation: 11486
The fact that you have used the assignment operator to throw the Exception in the following line:
USER_ID = getUserIdFromEnvironment();
means that the compiler thinks that there is a possibility of assignment, especially given the fact that it is declared as final
.
Upvotes: 4
Reputation: 1066
Since the compiler gave you an that kind of error indicatesthat the variable has been creaated (and perhaps changed) somewhere else. It is good to change the name of your variable whereever it appears in your code.
Upvotes: 0
Reputation: 726479
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;
}
Upvotes: 19