kibar
kibar

Reputation: 824

Java getting nullpointerexception

mainMethod.java

public class mainMethod{
    public animalsData[] animals;

    public mainMethod(){
        animals[this.animals.length + 1] = new animalsData("CAT", "4");

    }

    public static void main(String[] args) {
        mainMethod run = new mainMethod();
    }
}

animalsData.java

public class animalsData{
    String name, l;

    public animalsData(String name, String l) {
        super();
        this.name= name;
        this.l= l;
    }
}

I hava this problem: Exception in thread "main" java.lang.NullPointerException

Upvotes: 3

Views: 159

Answers (3)

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33544

1. Array must be initialized when its declared.

Eg:

public animalsData[] animals; 


    public static void main(String[] args) {
        mainMethod run = new mainMethod();
        System.out.println(run.animals.length);
    }

The above code gives a NullPointerException, cause animals which is an Object Reference Array Variable is Null and is not assigned the Array Object on the heap.

public animalsData[] animals = new animalsData[10]; 


        public static void main(String[] args) {
            mainMethod run = new mainMethod();
            System.out.println(run.animals.length);
        }

The above code works fine....as the Array is now initialized.

I would recommend you to use java.util.Collections instead of arrays, they are very flexible.

List<animalsData> animals = new ArrayList<animalsData>();

Upvotes: 1

jdevelop
jdevelop

Reputation: 12306

public List<animalsData> animals = new ArrayList<animalsData>()

public mainMethod(){
    animals.add(new animalsData("CAT", "4"));
}

learn more about Lists in Java, arrays are not expandable by default. And can not expand beyond it's dimension if you add an item after last item of the array.

Upvotes: 4

Colin D
Colin D

Reputation: 5661

You are never initializing your animals array in your mainMethod class.

In your public mainMethod() method, you need to do animals = new animalsData[INITIAL SIZE];

If you want it to grow automatically, you should use a List. Even then you would not use this.animals.length + 1 as its index. you would simply do List.add()

Upvotes: 6

Related Questions