Skip to content

Can’t use array of objects

I have a Main and a Cars classes, and I am trying to create an array of Cars and have it like this:

public class Cars {

    protected String brand;
    protected int price;
    protected Cars[] list;
    Scanner keyboard;
    public Cars() {
        keyboard=new Scanner(;
    public void carList() {
        int nv;
        System.out.println("number of cars");
        Cars [] list = new Cars[nv];

then I have this for:

for(int i=0; i<list.length;i++){

to try and fill it but I get this error:

Cannot assign field "brand" because "list[i]" is null

Can you help me pointing what I’m doing wrong please?



You create Cars array, as:

Cars[] list = new Cars[nv];
/* two smells here:
   1. Cars (plural) as a type, and having array of Cars objects.. that is Cars of cars;
   2. don't name arrays as list.. lists are another type.

but you never put any car instance into that array.

Afterwards, with:


you are trying to fetch the ith element from the list array and access its field, but you have nulls in your array (which is the default value array of reference type is initialized with), therefore, fields brand and price will not be resolved as you’re accessing them on the null reference.

Instead, you should first create an object(s) and put that(those) into your array.

User contributions licensed under: CC BY-SA
3 People found this is helpful