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)
carrotArray[1]Also, use capital first letters for classes, i.e. Apples and CarrotscarrotArray[1] = new carrots();beforecarrotArray[1].setVar(10);.