2

I keep getting this error:

Exception in thread "main" java.lang.NullPointerException
    at Circle.main(Circle.java:35)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)

I'm trying to set the attributes for the first circle object, but I guess I can't do this in java this way?

public class Circle {
    private double x,
                   y,
                   radius;

    public static void main(String args[]) {
        // Testing Circles
        System.out.println("\nTESTING CIRCLES:");
        Circle[] circles = new Circle[2];
        Circle circle1 = circles[0]; // Circle 1

        // Setting X
        circle1.setX(20);  // <- Why does this not work and how is this properly done.
    }

    public void setX(double xVal) {
        x = xVal;
    }
}

1 Answer 1

3

You have not initialized your Circle object, just declared an empty array that is fit to hold circle objects. At the time of declaration, all objects in the array are null. You need to initialize the objects in the array before you're able to call methods on them.

Circle[] circles = new Circle[2];
circles[0] = new Circle();
circles[0].setX(20);

Or you can do initialization and declaration in one line as follows:

Circle[] circles = new Circle[] { new Circle(), new Circle() };
circles[0].setX(20);
Sign up to request clarification or add additional context in comments.

2 Comments

The latter is wrong because you can't have both a dimension expression and an array initializer. It should be Circle[] circles = new Circle[] { new Circle(), new Circle() };, or better, Circle[] circles = { new Circle(), new Circle() };
@johnchen902 My bad. Correcting my answer.

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.