Search code examples
javaarraysfunctionobjectinitialization

How to fill an array with objects in a function whereas I declared this array in the main function?


when I try to fill an array with objects in a function, I always get an error even if the array is declared beforehand in the main function. I'm also a beginner in OOP.

This is my Point class :

public class Point {
    private int positionX;
    private int positionY;

    public Point(int positionX, int positionY) {
        this.positionX = positionX;
        this.positionY = positionY;
    }

    public int getPositionX() {
        return positionX;
    }

    public void setPositionX(int positionX) {
        this.positionX = positionX;
    }

    public int getPositionY() {
        return positionY;
    }

    public void setPositionY(int positionY) {
        this.positionY = positionY;
    }
}

And this is my Main class :

public class Main {

    public static void setupPointArray(Point ptArr[]) {
        ptArr = new Point[] {new Point(2, 3),
                             new Point(4, 1),
                             new Point(6, 2)};
    }

    public static void main(String[] args) {
        Point pointArray[] = new Point[3];
        setupPointArray(pointArray);

        System.out.println(pointArray[0].getPositionX() + pointArray[0].getPositionY());
        System.out.println(pointArray[1].getPositionX() + pointArray[1].getPositionY());
        System.out.println(pointArray[2].getPositionX() + pointArray[2].getPositionY());
    }

}

But I get an error in the console.

Exception in thread "main" java.lang.NullPointerException
    at fr.antonin.point.Main.main(Main.java:15)

Solution

  • You're modifying a local variable, the formal parameter. It doesn't affect the actual parameter.

    public static void setupPointArray(Point ptArr[]) {
        ptArr = new Point[] {new Point(2, 3),
                             new Point(4, 1),
                             new Point(6, 2)};
    }
    

    You could resolve this either by returning the array you created, or by filling the original array you pass. For example:

    public static Point[] setupPointArray() {
        return new Point[] {new Point(2, 3),
                             new Point(4, 1),
                             new Point(6, 2)};
    }
    

    Or, you could fill the passed array - if you're sure of its length:

    public static void setupPointArray( Point[] ptArr ) {
        ptArr[0] = new Point(2, 3);
        ptArr[1] = new Point(4, 1);
        ptArr[2] = new Point(6, 2);
    }