0

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)
3
  • 1
    You need to fill the array with objects yourself. You get a NPE here: carrotArray[1] Also, use capital first letters for classes, i.e. Apples and Carrots Commented Jan 11, 2014 at 1:15
  • carrotArray[1] = new carrots(); before carrotArray[1].setVar(10);. Commented Jan 11, 2014 at 1:18
  • Thanks to both of you for your replies! Commented Jan 11, 2014 at 1:20

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.