0

I tried executing the following code

public class Phonebook {
    String name;
    long phno;
}

public class Store {
    public static void main(String args[]) {        
        Phonebook p[] = new Phonebook[10];

        p[0].name = "vasvi";
        p[0].phno = 123456;
        p[1].name = "abcd";
        p[2].phno = 903747;

        System.out.println(p[0].name + " " + p[1].name);
    }
}

This code when executed gives the NullPointerException. I don't seem to understand why. I have learnt that classes are user defined data types. So I'm really confused why such an exception would arise?

Jacob G.
  • 28,856
  • 5
  • 62
  • 116
Vasvi Sood
  • 29
  • 1
  • 5
  • 2
    Your array is empty, you never put `Phonebook` objects in it . Sure it has 10 slots, but each one contains `null` . – Arnaud Apr 07 '20 at 14:02

1 Answers1

0

it looks like you have not initialized you array.

jcoleau
  • 1,112
  • 7
  • 20