106

I'm working in Java.

I commonly setup some objects as such:

public class Foo {
    private SomeObject someName;

    // do stuff

    public void someMethod() {
        if (this.someName != null) {
            // do some stuff
        }
    }
}

The question is: Is someName in this example equated to null, as-in I can reliably for all objects assume null-checking uninitialized objects will be accurate?

SnakeDoc
  • 13,611
  • 17
  • 65
  • 97

2 Answers2

129

Correct, both static and instance members of reference type not explicitly initialized are set to null by Java. The same rule applies to array members.

From the Java Language Specification, section 4.12.5:

Initial Values of Variables

Every variable in a program must have a value before its value is used:

Each class variable, instance variable, or array component is initialized with a default value when it is created

[...] For all reference types, the default value is null.

Note that the above rule excludes local variables: they must be initialized explicitly, otherwise the program will not compile.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • how does this apply to, for example, `char` ? I can do `char test;` but not `char test = null;` – xorinzor Sep 26 '17 at 13:40
  • 2
    @xorinzor You cannot assign `null` to `char` because it is a primitive type. Also you cannot do `char test;` inside a method without assigning `test` later on. You can do `char test='a'` if you want, or leave it as `char test;` in a member declaration to get the default value of `'\0'`. – Sergey Kalinichenko Sep 26 '17 at 13:47
17

If an Object reference has been declared but not instantiated, its value is null.

Jared Nielsen
  • 3,669
  • 9
  • 25
  • 36