-2

I am adding objects to an ArrayList that is initialized as null inside a for each loop, but SonarLint is giving me a "NullPointerException" could be thrown when I try to add each object. Why is this error being pointed out?

public List<SatelliteData> getData()
  {
    SatelliteData satellite;
    ArrayList<SatelliteData> satelliteList = null;

    try(FileInputStream file = new FileInputStream(satelliteOutputFile))
    {
      TLEParser parsedFile = new TLEParser();
      List<TLE> tleList = parsedFile.readFile(file);

      for (TLE tle : tleList)
      {
        satellite = new SatelliteData(tle);
        satellite.collectSatelliteData();

        satelliteList.add(satellite); //A "NullPointerException" could be thrown; "satelliteList" is nullable here
      }

    }
    catch (IOException ex)
    {
      LOGGER.error("IO Exception: " +  ex);
      notifyTheObservers("IO Exception: " + ex);
    }

    return satelliteList;
  }
Emma Barrett
  • 83
  • 1
  • 10
  • what do you mean by "Why is this error being pointed out?", are you not expecting a NPE here? – Pankaj Gadge Dec 07 '17 at 20:53
  • 2
    Because you never initialize `satelliteList`. – Marvin Dec 07 '17 at 20:53
  • 1
    NullPointerException can be thrown because you are trying to call methods on a null object. You need to actually create `satelliteList` somewhere like `satelliteList = new ArrayList();` – takendarkk Dec 07 '17 at 20:58

1 Answers1

2

You shouldn't call member methods on variables that have been initialized to nothing/null.

In this case you have

ArrayList<SatelliteData> satelliteList = null;

This variable does not have any memory allocated to it.

At this point your computer knows : Okay there exists something called satelliteData but it actually doesn't know where it is?

Calling add() method on it, is likely to throw a NullPointerException because this variable is a reference that is pointing to null/nothing.

To overcome this, You need to initialize the variable like this :

ArrayList<SatelliteData> satelliteList = new ArrayList<SatelliteData>();

At this point your computer created that satteliteData and knows exactly where it exists hence it can happily operate upon it.

This will allocate some memory to this variable and now it has its own methods you can call.

coder3101
  • 3,920
  • 3
  • 24
  • 28