6

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.

davison
  • 335
  • 1
  • 3
  • 16

1 Answers1

8

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.

brso05
  • 13,142
  • 2
  • 21
  • 40
  • makes sense . In a method scope what value does Java give it on its own? Is it some unknown garbage value ? – davison Nov 10 '14 at 22:02
  • 3
    Note that it's not initializing an *object* - it's initializing a *variable*. They're very different things. – Jon Skeet Nov 10 '14 at 22:03
  • agreed!! its initializing the reference to the object. – davison Nov 10 '14 at 22:03
  • @davison: it doesn't give it any value of its own, since it forces you to explicitely initialize it. – JB Nizet Nov 10 '14 at 22:29
  • @davison It doesn't give it *any value* in local scope. It insists that *you* do, otherwise it won't compile the code. – user207421 Nov 10 '14 at 23:08
  • To put it another way: if it is an object field it will get default value if not assigned explicitly. If it is a variable declared within a method you have to provide explicit initialisation. – Artur Nov 13 '14 at 09:06