1

I keep getting a NullPointerException for an array of objects I created that hasn't been initialized. But my player class has a default contructor so I assumed it would be fine. Why can't I call an instance method with these objects?

My main code block:

public class Blackjack{
  public static void main(String[] args){
    Player[] p;
    p = new Player[6];
  }
}

And here is my player constructor:

public class Player {

    private int money;
    private int bet;
    private int handValue;

    // Player Constructor
    public Player() {
        handValue = 0;
        money = 100;
        this.bet = 0;
    }
}
zapl
  • 63,179
  • 10
  • 123
  • 154
paul huang
  • 11
  • 3

4 Answers4

1

After you instantiate the array, you must instantiate each individual element of the array with :

p[i] = new Player();

before you can call methods for those elements, since until you do that, p[i] contains null for each i.

Eran
  • 387,369
  • 54
  • 702
  • 768
1

Player[] p; p = new Player[6]; this will make p refer to an array of 6 null elements . new Player[6]; doesn't run the constructor

Ramanlfc
  • 8,283
  • 1
  • 18
  • 24
1

Arrays are containers. In case of Objects they hold references. You can compare your code to

class PlayerContainerWith3Elements {
    public Player element0; // default initialized with null
    public Player element1;
    public Player element2;
}

PlayerContainerWith3Elements p = new PlayerContainerWith3Elements();
p.element0.helloNullPointer();

It's just much more convenient not to invent a class for every length and type and instead make a container via new Player[3]. But like a manual container, you have to set the reference for all the elements individually. In small arrays via the initializer syntax:

Player[] p = new Player[]{ new Player(), new Player(), new Player()};
// => makes a new Player[3] and puts the three objects in the 3 slots.

Anything larger with a loop

Player[] p = new Player[3];
for (int i = 0; i < p.length; i++)
    p[i] = new Player();

Or in Java 8 you can do

Player[] p = Stream.generate(Player::new).limit(3).toArray(Player[]::new);
zapl
  • 63,179
  • 10
  • 123
  • 154
0

Your code creates an empty array of size 6

Player[] p;
p = new Player[6];

p is now: { null, null, null, null, null, null }

Instead, you want to fill this array with Player-objects, so try this instead:

Player[] p = new Player[6];
for (int i = 0; i < p.length; i++){
    p[i] = new Player();
}

p is now: { aPlayerInstance1, aPlayerInstance2, aPlayerInstance3, aPlayerInstance4, aPlayerInstance5, aPlayerInstance6 }

Kevin Cruijssen
  • 9,153
  • 9
  • 61
  • 135