Search code examples
javanullinitialization

Why Initializing References to Null Is allowed In Java?


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.


Solution

  • 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.