Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 935
davison Avatar asked Nov 10 '14 21:11

davison


People also ask

Can we initialize reference to null?

No, references cannot be NULL in C++. Possible solutions include: using a pointer instead of a reference.

Can reference be null in Java?

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.

Does Java initialize to null?

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.

Is it good practice to initialize string to null?

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.


1 Answers

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.

like image 159
brso05 Avatar answered Sep 18 '22 00:09

brso05