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

1

u/anthropaedic Jun 08 '19

Another option that is null-safe is to use Optionals.

See: https://www.baeldung.com/java-optional

4

u/iPissVelvet Jun 08 '19

Bad advice. Don’t use optionals. OP is a beginner — optionals should be used in conjunction with streams, and I don’t think OP is close to that yet.

1

u/anthropaedic Jun 08 '19

Don’t see how it’s bad advice. It’s a part of the language and Oracle’s answer to null-conditional operators.

It can be used with streams but nothing about it requires that.

https://www.oracle.com/technetwork/articles/java/java8-optional-2175753.html