-1

Getting a null pointer exception how would I avoid this because I have to try to find if the array has null value and notify if it has null value . Right now it just puts up a NPE.

 String [] s = {null,"first","890808908","4545645646","989809908098","65756756757","second"};
       for (String word : s){
           if (!word.equals("first") && !word.equals("second") && word == null){
               System.out.println("yes there is null value");
           }
       }
      }
KKir
  • 11
  • 4

3 Answers3

1

Well the immediate null pointer exception in your code could be avoided by rephrasing how you examine the string:

if (!"first".equals(word) && !"second".equals(word) && word == null) {
    System.out.println("yes there is null value");
}

Note that "first".equals(word) is valid even when word is null. But really all you need to do is to check explicitly for a null value, so just use:

if (word == null) {
    System.out.println("yes there is null value");
}
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

You need to check for null before your other conditions. You are trying to call word.equals(...) but there is the case where word is null. Null does not have any methods, hence the NPE.

Additionally, your logic just reduces to word == null since you have AND conditions and the condition where word == null fulfils all the other conditions, so you can just reduce it to:

public static void main(String args[]) {
        String [] s = {null,"first","890808908","4545645646","989809908098","65756756757","second"};
       for (String word : s){
           if (word == null){
               System.out.println("yes there is null value");
           }
       }
      }
Joshua Lewis
  • 166
  • 4
0

you can use this code :

public class Avoid_NullPoint {
    public static void main(String args[]) {
        String [] s = {null,"first","890808908","4545645646","989809908098","65756756757","second"};
        for (String word : s){
            if (word == null && word !="first" && word !="second" ){
                System.out.println("yes there is null value");
            }

    }
}