user3183947
user3183947

Reputation: 11

Calling methods from other classes using array objects in Java

Why does this code not work? It seems I cannot set the variable to '10' with the Array, but with a normal object it works.

What am I doing wrong?

Class- 1

public class apples {
    public static void main(String[] args) {
        carrots carrotObj = new carrots();      
        carrotObj.setVar(5);        
        System.out.println(carrotObj.getVar());

        carrots carrotArray[] = new carrots[3];
        carrotArray[1].setVar(10);        
        System.out.println(carrotArray[1].getVar());
    }
}

Class- 2

public class carrots { 
    private int var = 0;
    public int getVar() {
        return var;
    }

    public void setVar(int var) {
        this.var = var;
    }
}

Console Output:

5
Exception in thread "main" 
java.lang.NullPointerException
    at apples.main(apples.java:17)

Upvotes: 0

Views: 95

Answers (2)

le-doude
le-doude

Reputation: 3367

You need to initialize all the elements of the array; since they are not primitive data types their default value is null.

carrots carrotArray[] = new carrots[3];
for(int i=0; i < carrotArray.length; i++){
   carrotArray[i] = new carrots();
}
carrotArray[1].setVar(10);

System.out.println(carrotArray[1].getVar());

Upvotes: 0

rgettman
rgettman

Reputation: 178263

You created an array, but when an array of objects is created, they are all initialized to null -- the default value for object reference variables. You need to create some objects and assign them to slots in the array.

carrots carrotArray[] = new carrots[3];

// Place this code
carrotArray[1] = new carrots();

carrotArray[1].setVar(10);

You could do something similar for position 0 and 2.

Additionally, the Java convention is to capitalize class names, e.g. Carrots.

Upvotes: 1

Related Questions