r/javahelp • • Jun 08 '19

Why is there a NullPointerException?

Hi all!

Please check my method below, for some reason I get NullPointerException for line 9.

countryArray is an array of strings, with countries, but then it is also filled with a bunch of null after the list of countries is over.

  1.     public static void golds(String[] countryArray) {

  2.         //int count = 0;

  3.         String currentCountry = new String();

  4.         for (int i = 0; i < countryArray.length; i++) {

  5.             currentCountry = countryArray[i];

  6.             int count = 0;

  7.             for (int j = 0; j < countryArray.length; j++) {

  8.                 if (countryArray[j] != null) {

  9.                     if (currentCountry.equals(countryArray[j])) { // FIX THE NULL POINTER ERROR!!!!!!!!!

  10.                         count++;

  11.                     }

  12.                 }

  13.                 else {

  14.                     j = countryArray.length;

  15.                 }

  16.             }

  17.         }

  18.         countryArray = removeDuplicates(countryArray);

  19.         System.out.println("Count of gold medalists by country:");

  20.         for (int g = 0; g < countryArray.length; g++) {

  21.             System.out.println(countryArray[g]);

  22.         }

0 Upvotes

16 comments sorted by

View all comments

2

u/lbkulinski Jun 08 '19

Did you initialize the elements of your array? They are null by default, which would be why currentCountry is null.

1

u/Madridi77 Jun 08 '19

The array countryArray is ~ half filled with countries and ~ half filled with null

2

u/lbkulinski Jun 08 '19 edited Jun 08 '19

Well currentCountry is null. Trying to invoke a method on a null reference will throw a NullPointerException. Are you trying to incorporate nulls into your equality check?

1

u/Madridi77 Jun 08 '19

What am trying to do is, when the comparison reaches a null, it should go to the else statement. Because I know once the first null appears, everything after it in the array is also null, so no reason to waste time comparing.

3

u/lbkulinski Jun 08 '19 edited Jun 08 '19

I see, but you are still storing a null in currentCountry. That is your issue.

1

u/Madridi77 Jun 08 '19

How should I go on about fixing it?

Should I initialize by doing String currentCountry = ""; ?

1

u/lbkulinski Jun 08 '19

I believe your issue is can be fixed by setting i equal to countryArray.length. Currently your outer loop is still accessing null elements.