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?
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.
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.
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.
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.
You can't reassign a finale Variable! You gotta change your
final Reader reader;
to
Reader reader = null;
and give reader a initial value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With