Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiler says "Variable might not have been initialized", although I have a flag variable to guarantee it [duplicate]

Tags:

java

Here is my code snippet:

Someclass someObject;
boolean success = true;
try {
    someObject = someOperation();
} catch (Exception e) {
    success = false;
}
if (success) {
    int number = Integer.valueOf(someObject.someMethord());
}

and within the line:

 int number = Integer.valueOf(someObject.someMethord());

the Java compiler throws and error saying

Error: variable someObject might not have been initialized`.

However, if success equals true, then there is no way someObject will not have been initialized, why am I getting this error?

like image 642
user2916610 Avatar asked Dec 01 '17 09:12

user2916610


People also ask

Why does it say variable might not have been initialized?

If the compiler believes that a local variable might not have been initialized before the next statement which is using it, you get this error. You will not get this error if you just declare the local variable but will not use it.

Why is my variable not initialized Java?

This error occurs only for local variables since Java automatically initializes the instance variables at compile time (it sets 0 for integers, false for boolean, etc.). However, local variables need a default value because the Java compiler doesn't allow the use of uninitialized variables.


1 Answers

The compiler doesn't analyze the relation between your success flag and the initialization of the someObject variable.

As far as the compiler is concerned, someObject may not be initialized if an exception occurs.

You can solve that issue by setting the variable to null in your catch block (and instead of checking your success variable, check that someObject != null).

Or you can move the int number = Integer.valueOf(someObject.someMethord()); statement inside your try block.

like image 89
Eran Avatar answered Oct 15 '22 12:10

Eran