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

5.1 Arrays — default values and arrays of objects

Lesson

Что лежит в массиве до того, как вы туда что-то положили

new int[3] does not leave garbage — Java fills the slots with a default: 0 for numbers, false for booleans, and null for anything that holds an object, including String.


Осторожно с массивом объектов

Dog[] pack = new Dog[2];
System.out.println(pack[0]);   // null — НЕ собака!

This is the trap: new Dog[2] creates room for two dogs, but no dogs. Every slot is null until you build an object and put it there. Touching pack[0].name right away crashes with a NullPointerException.

Rule: creating an array of objects and filling it are two separate steps.


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



new int[3] fills the slots with...


new Dog[5] creates...


Type exactly what this program prints.

public class Main { public static void main(String[] a){
    int[] n = new int[2];
    String[] s = new String[2];
    System.out.println(n[1]);
    System.out.println(s[1]);
}}

Why does pack[0].name crash right after new Dog[2]?


True or false?