Java: Arrays

In some posts on SO we see something like this:

public class XYZ {
   private double dNumbers[];

   public XYZ() {
      // do something


   public void addNumber(double d) {
      dNumbers[0] = d;
      dNumbers[1] = d;
      // ...



This wont work and you’ll get a NullPointerException!! Why?

// declarate an array of type double
// it is able to store double values but has no dimension defined
private double dNumbers[];

// maybe you check this and do this in your constructor
public XYZ(int size) {
  // now you can add values and no NP Exception is thrown!
  dNumbers = new double[size];