In the following example that uses JDBC (this question though is not specific to JDBC):
Connection conn = null;
try
{
..... Do the normal JDBC thing here ....
}
catch(SQLException se)
{
if(conn != null)
{
conn.close();
}
}
If I do not initialize the conn
to null
then the compiler complains that in the catch
block I cannot use a reference that has not been initialized.
Java by default initializes a object reference to null then why do I need to explicitly initialize it to null. If the compiler did not like the original value of the reference which was null to start with , why did it even accept my explicit initialization?
NOTE: I am using Eclipse Luna
as my IDE.
No, references cannot be NULL in C++. Possible solutions include: using a pointer instead of a reference.
In Java programming, null can be assigned to any variable of a reference type (that is, a non-primitive type) to indicate that the variable does not refer to any object or array.
They are null by default for objects, 0 for numeric values and false for booleans. For variables declared in methods - Java requires them to be initialized.
Most often I would say: don't initialize your local variable at all when declaring it, if it would be a dummy value like "" or null . Put the real value in, or wait until you can put it in. The compiler then will make sure that there is at least one assignment before any possible use of the variable.
It will only initialize a variable to null in the class scope. You are in a method scope so you must explicitly initialize the variable to null.
If the variable is defined at the class level then it will be initialized to null.
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