Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Might not have been initialized error at null check

I'm checking if the variable is initialized but at that point netbeans is giving me variable reader might not have been initialized warning. How do I fix/suppress this?

This is my code (summary):

final Reader reader;
try {
        reader = new Reader(directory);
        //additional stuff that can cause an exception
    } catch (Exception ex) {
        //do stuff
    } finally {
        if (reader != null);
    }

The point of the if check is to determine whether it is initialized.

And what is the best practice for this?

like image 995
WVrock Avatar asked Jun 08 '15 06:06

WVrock


People also ask

What does it mean if a variable has not been initialized?

Initializing a variable means specifying an initial value to assign to it (i.e., before it is used at all). Notice that a variable that is not initialized does not have a defined value, hence it cannot be used until it is assigned such a value.

Can you initialize a variable to null?

You should initialize your variables at the top of the class or withing a method if it is a method-local variable. You can initialize to null if you expect to have a setter method called to initialize a reference from another class. You can, but IMO you should not do that. Instead, initialize with a non-null value.

How do you initialize in Java?

The syntax for an initializer is the type, followed by the variable name, followed by an equal sign, followed by an expression. That expression can be anything, provided it has the same type as the variable. In this case, the expression is 10, which is an int literal.


2 Answers

If reader was never initialized, it doesn't even have a null value.

change

final Reader reader;

to

Reader reader = null;

to make sure it has an initial value.

This way, if reader = new Reader(directory); throws an exception, reader will contain null when tested by the finally block.

like image 192
Eran Avatar answered Oct 01 '22 12:10

Eran


You can't reassign a finale Variable! You gotta change your

final Reader reader;

to

Reader reader = null;  

and give reader a initial value.

like image 29
B. Kemmer Avatar answered Oct 01 '22 11:10

B. Kemmer