How to solve error when accessing object function in java?

Hi I'm creating a 2D array of objects in java and want to access one of the functions that simply returns the boolean value of the variable but for some reason, its throwing an error. The code looks so simple but I can't figure out what I am doing wrong. My guess is something to do with my implementation of the array, but I think I did it right. My goal is to create individual instances of the class for each value in the 100x100 grid.

Here is the code and error I am getting

public class Main {

    public static void main(String[] args) {
        ParkingLot parkingLot = new ParkingLot("Rushi's Parking lot", 100, 100);

        Vehicle car1 = new Car("License");


public class ParkingLot {
    String name;
    ParkingSpot[][] parkingGrid;

    public ParkingLot(String name, int xSize, int ySize){ = name;
        this.parkingGrid = new ParkingSpot[xSize][ySize];

    public void registerVehicle() {

    public void getNextSpot(Vehicle vehicle){


public class ParkingSpot {
    private boolean available = true;
    private String license;
    private int time;

    public boolean isAvailable() {
        return available;

    public void reserveSpot(String license){
        this.license = license;
        this.available = false;


Exception in thread "main" java.lang.NullPointerException
    at ParkingLot.registerVehicle(
    at Main.main(

2 answers

  • answered 2020-08-03 21:45 stefan.mih

    Where did you added vehicle? Array is empty, of course it will throw null pointer because there is no any data in it. You need method for adding vehicles and registering positions so you can move to next one when you add vehicle also.

  • answered 2020-08-03 21:46 Morinator

    When you create an object of type ParkingLot, the array parkingGrid only contains null-references. You need to actually add the parking spots you want to use.
    So far you only specified that parkingGrid has size 100x100 and contains parking spots, but the individual elements aren't there.