davison
davison

Reputation: 335

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.

Upvotes: 6

Views: 311

Answers (2)

Joop Eggen
Joop Eggen

Reputation: 109567

Some further explanation, as java uses two different rules of initialisation.

Fields of a class are initialized (0, null, false, ...). This was language design is done to prevent errors on unitialized fields. And because initializing to defaults happens often.

Variables in a method are not initialized. This langage design decision was taken as otherwise errors could occur, of defaulted values (hence unseeen statements). It makes sense to introduce a variable for its value. To declare a variable near its usage, and in effect immediately assign to it.

Upvotes: 0

brso05
brso05

Reputation: 13232

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.

Upvotes: 9

Related Questions