Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring an object of a class as null

When we only declare an object of a class without instantiating it like below, does it treats as null or empty or else?

Example1: Directory objDEntry;

Example2: Directory objDEntry = null;

Is there a difference between Example1 and Example2 or they are same?

like image 351
Zakir HC Avatar asked Sep 03 '25 15:09

Zakir HC


1 Answers

It depends; if you declare a field, e.g.

  public class MyClass {
    // objDEntr will be initialized by null
    Directory objDEntr;
    // the initialization is redundant here
    Directory objDEntry2 = null;  
    ... 

there's no difference, since fields are initialized by their default values and null is the default value for reference types. However, local variables are not initialized by default; so

  public static void MyMethod() {
    // objDEntry contains trash, must be initialized further
    Directory objDEntry; 
    // objDEntry2 is null
    Directory objDEntry2 = null;  
    ...

in the "Example 1" objDEntry contains trash, while in the "Example 2" objDEntry is properly initialized and contains null.

like image 193
Dmitry Bychenko Avatar answered Sep 05 '25 04:09

Dmitry Bychenko