My code is throwing a NullPointerException, even though the object seems to properly exist.
public class IrregularPolygon { private ArrayList<Point2D.Double> myPolygon; public void add(Point2D.Double aPoint) { System.out.println(aPoint); // Outputs Point2D.Double[20.0, 10.0] myPolygon.add(aPoint); // NullPointerException gets thrown here } } // Everything below this line is called by main() IrregularPolygon poly = new IrregularPolygon(); Point2D.Double a = new Point2D.Double(20,10); poly.add(a);
Why is this happening?
In Java, the java. lang. NullPointerException is thrown when a reference variable is accessed (or de-referenced) and is not pointing to any object. This error can be resolved by using a try-catch block or an if-else condition to check if a reference variable is null before dereferencing it.
What Causes NullPointerException. The NullPointerException occurs due to a situation in application code where an uninitialized object is attempted to be accessed or modified. Essentially, this means the object reference does not point anywhere and has a null value.
The Java collection classes, including ArrayList, have one major constraint: they can only store pointers to objects, not primitives. So an ArrayList can store pointers to String objects or Color objects, but an ArrayList cannot store a collection of primitives like int or double.
Answer: Some of the best practices to avoid NullPointerException are: Use equals() and equalsIgnoreCase() method with String literal instead of using it on the unknown object that can be null. Use valueOf() instead of toString() ; and both return the same result. Use Java annotation @NotNull and @Nullable.
based on the parts of the code you provided, it looks like you haven't initialized myPolygon
private ArrayList<Point2D.Double> myPolygon = new ArrayList<Point2D.Double>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With