Task 8 of 10 · 0 solved · 10 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

4.1 Objects and fields — references and null

Lesson

Переменная хранит не объект, а ссылку на него

When you write Dog d = new Dog("Rex");, the variable d does not contain the dog. It contains a reference — the address where the object lives. That is why two variables can point at the same object, and why a variable can point at nothing.

Pointing at nothing is written null. A field of object type that was never assigned is null too.


Worked example

Dog nobody = null;
System.out.println(nobody);           // null
System.out.println(nobody == null);   // true

System.out.println(nobody.name);      // CRASH: NullPointerException

The crash message is explicit: Cannot read field "name" because ... is null. There is no object, so there is no field to read.

Guard with a check before you touch anything: if (d != null) { ... }. This is the single most common runtime error in Java.


▶ Try it: run this, then change something and run it again.



What does a variable of object type actually hold?


null means...


Type exactly what this program prints.

class Dog {
    String name;

    Dog(String name) {
        this.name = name;
    }
}

public class Main {
    public static void main(String[] a){
        Dog d = null;
        System.out.println(d == null);
        d = new Dog("Bo");
        System.out.println(d == null);
        System.out.println(d.name);
    }
}

Reading a field of a null reference causes...


True or false?