TwoShorts
TwoShorts

Reputation: 548

Java Nullpointer exception while creating array

I am trying to create an array of boats, containing RaceBoat objects and SailBoat objects. Currently I have this:

Boat[] boats;

totalBoatCount = args.length;

for (int i = 0 ; i < totalBoatCount ; i++)
    {
       char firstChar = boatNames[i].charAt(0);

        if (Boat.isItRaceBoat(firstChar)) 
        {
           boats[i] = new RaceBoat(boatNames[i]);
        } 
        else 
        {
            boats[i] = new SailBoat(boatNames[i]);
        }
    }

every time I create a new SailBoat or RaceBoat, I get a java.lang.NullPointerException. How am I supposed to phrase this to create this array?

Upvotes: 0

Views: 87

Answers (4)

rachana
rachana

Reputation: 3424

Boat[] boats must have to be initialized

    Boat[] boats = new Boats[args.length];

    for (int i = 0 ; i < boats.length ; i++)
    {
            char firstChar = boatNames[i].charAt(0);

           if (Boat.isItRaceBoat(firstChar)) 
           {
                boats[i] = new RaceBoat(boatNames[i]);
           } 
           else 
           {
                boats[i] = new SailBoat(boatNames[i]);
           }
    }

Upvotes: 0

kapukinz
kapukinz

Reputation: 185

The array "boats" is not initialized, which means it is null.

Upvotes: 2

user2720864
user2720864

Reputation: 8171

Boat[] boats must have to be initialized before you assign
boats[i] = new RaceBoat(boatNames[i]);

Upvotes: 1

Alex A.
Alex A.

Reputation: 2736

Boat[] boats;

just declares a Boat[] variable. You also need to instantiate it with

Boat[] boats = new Boat[args.length];

The part of the line before '=' states that boats is an array that contains Boat instances. The part after it actually constructs this empty array object (able to contain args.length number of Boat instances) and assigns it to the boats variable.

Upvotes: 4

Related Questions