Why Initializing References to Null Is allowed In Java?
Asked Answered
G

2

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.

Grizel answered 10/11, 2014 at 21:58 Comment(3)
Your title has nothing to do with your question.Merengue
At the time of asking this question (with the knowledge that I had) the title made proper sense to me. In hindsight of course .... :)Grizel
You should close connection in the finally block, I think.Coroner
F
9

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.

Frenzy answered 10/11, 2014 at 21:59 Comment(6)
makes sense . In a method scope what value does Java give it on its own? Is it some unknown garbage value ?Grizel
Note that it's not initializing an object - it's initializing a variable. They're very different things.Donadonadee
agreed!! its initializing the reference to the object.Grizel
@davison: it doesn't give it any value of its own, since it forces you to explicitely initialize it.Dovetailed
@Grizel It doesn't give it any value in local scope. It insists that you do, otherwise it won't compile the code.Merengue
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.Babble
L
0

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.

Lydie answered 26/8 at 9:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.