0

Hello friends am trying to work on resolving NUllpointer Exception that is being thrown with in this code

 public String getInvalidPhoneNumberNotification() {
        List<String> errors = getValidationErrors();
        String search = "valid phone number";
        for (String str : errors) {
            if (str.trim().contains(search))
             return str;
        }
        return null;
    }

i have read through different ways of how i can get rid of using return null object in order to catch npe but it seems the problem still persits, am using getInvalidPhoneNumberNotification() method reference to handle whether the method is an integer, but the problem is returning null object when its already null, any help will be appreciated

Sharif
  • 9
  • 6
  • In which line does the NPE occur? I would assume that either errors is null (NPE in the for-statement-line) or one element of errors is null (NPE in if-statement-line) – Mathias Jun 22 '21 at 09:25
  • 1
    And where is the NPE? Check that `getValidationErrors()` is not returning a `null`, and that it doesn't contain `null` strings. – Óscar López Jun 22 '21 at 09:26
  • seems your 'getValidationErrors()' method is returning null. If this is case, can you apply null check before for loop? – Ashish Patil Jun 22 '21 at 09:34
  • If that's the case, then I would argue the fix is having `getValidationErrors` return an empty list instead of null, instead. – Federico klez Culloca Jun 22 '21 at 09:38
  • Thanks everyone, the problem is within the loop, String search = "valid phone number"; for (String str : errors) { System.out.println("string inside error is " + str); if (str.trim().contains(search)) return str; } return null; } – Sharif Jun 22 '21 at 10:05

0 Answers0