Reputation: 9010
Whenever I declare a local variable in a method and then assign values to it in a conditional like if/else block or try/catch, and then try to return the variable, I get the compiler error
The local variable XXX may not have been initialized
I understand that the if/else or try/catch block might not be executed under certain conditions, and so the variable will not be initialized, and thus the error.
But more often than not, I come across code in which they do not initialize the variable and still it works. For example, on this page, see the following method:
public int getItemViewType ( int position ) {
int viewType;
if ( groups.get ( position ).getImagePath () != null ) {
viewType = TYPE_IMAGE;
} else {
viewType = TYPE_GROUP;
}
return viewType;
}
When I wrote the same method, I got the error on the return
statement. The only difference of my method from this one is that I have only if
and else-if
blocks, and no else
block.
Do people suppress this error through some annotation on the method or something, I don't think so.
So why don't they get the error, while I do?
Upvotes: 0
Views: 1573
Reputation: 5040
It works because when you reach the return statement, viewType
is guaranteed to have a value.
int viewType;
if ( groups.get ( position ).getImagePath () != null ) {
viewType = TYPE_IMAGE;
} else {
viewType = TYPE_GROUP;
}
return viewType;
It will have either TYPE_IMAGE
or TYPE_GROUP
In your code you might be doing some thing like :
int viewType;
try{
// some code which can cause an exception.
viewType=something;
} catch(Exception e){}
return viewType;
or
int viewType;
if(some condition){
viewType=something;
}
return viewType;
In both these cases, you can not guarantee that viewType
will have a value when you reach return statement.
If the try
block throws any exception or the condition fails in your if
block, viewType
will not have any value.
That is why you will get the error. But in the code you have posted it's not the case, the code guarantees to have some value.
Upvotes: 6