简体   繁体   中英

Getting java.lang.NullPointerException while returning an array of integers in java

public class Omit {

    int[] omitnum(int[] a) {
        int[] arr = null;
        for (int i = 0; i <= 7; i++) {
            if (a[i] >= 13 && a[i] <= 19) {
                System.out.print(a[i]);
            } else {
                arr[i] = a[i];
            }
        }
        return arr;
    }
    public static void main(String[] args) {
        Omit c = new Omit();
        int[] a = {
            1,
            2,
            3,
            12,
            113,
            14,
            19,
            20
        };
        int[] b = null;
        b = c.omitnum(a);
        for (int i = 0; i <= 7; i++) {
            System.out.println(b[i]);
        }
    }

}

}

Getting this error while running Exception in thread "main"

java.lang.NullPointerException
    at omit.Omit.omitnum(Omit.java:20)
    at omit.Omit.main(Omit.java:28)

Initialized an array to return some values but it isn't returning any values and giving null error

From the stack trace you posted in your question, line 20 in file Omit.java is throwing NullPointerException . Which line is line 20 in class Omit.java ? Could it be this line:

arr[i] = a[i];

That would mean that either arr is null or a is null. If you debug your program, you will discover which of them is null. (Perhaps both are null?)

Any decent java IDE includes a debugger. Decent java IDE's include Intellij , Eclipse , NetBeans and JDeveloper . I also suggest you readHow to debug small programs

Nonetheless, I see in this line of your code (which is the first line in method omitnum() ) that you are explicitly setting local method variable arr to null:

int[] arr = null;

After that line you never assign a different value to arr and hence, when you get to this line:

arr[i] = a[i];

the variable arr is still null and hence the NullPointerException . Refer to this stackoverflow question: What is a NullPointerException, and how do I fix it?

You need to initialize an array before you can use it. If you Google for the terms java initialize array , you will get several million results, including Initializing Arrays in Java .

You get NullPointerException meaning you try to access some variable that is null .

In java you need to initialize arrays before you can use them, and in your code you just set arr = null so this is why it's not working.

If you want it to work just define arr properly like:

int[] arr = new int[a.length];

That error means you are assigning to a null pointer, you could write arr[a.length] but that would allocate memory for more elements than you actually need, because you need to only store according to a condition, that way you should do it like this:

public class Omit {
  int[] omitnum(int[] a) {
    int maxNum = 0;
    // calculate how much memory needed
    for(int i = 0;i < a.length; i++) {
      if(!(a[i] >= 13 && a[i] <= 19)) {
        maxNum++;
      }
    }
    // --------------------------------
    int[] arr = new int[maxNum];
    for(int i = 0, j = 0; i < a.length; i++) {
      if(a[i] >= 13 && a[i] <= 19) {
        System.out.println("Deleted: " + a[i]);
      }else {
        /* we can't use `i` because that would gives an error
           because arr has less elements than a :) */
        arr[j++] = a[i];
      }
    }
    return arr;
  }

  public static void main(String[] args) {
    Omit c = new Omit();
    int[] a = {1, 2, 3, 12, 113, 14, 19, 20};
    int[] b = c.omitnum(a);
    for(int i = 0; i < b.length; i++) {
      System.out.println(b[i]);
    }
  }
}

Output:

Deleted: 14
Deleted: 19
1
2
3
12
113
20

and array.length gives you flexibility instead of looping to a static position, to avoid changing your code each time you add or remove elements, and from counting of course

Here is another way using ArrayLists

import java.util.ArrayList;

public class Omit {
  ArrayList omitnum(int[] a) {
    ArrayList<Integer> arr = new ArrayList<Integer>();
    for(int i = 0; i < a.length; i++) {
      if(a[i] >= 13 && a[i] <= 19) {
        System.out.println("Deleted: " + a[i]);
      }else {
        arr.add(a[i]);
      }
    }
    return arr;
  }

  public static void main(String[] args) {
    Omit c = new Omit();
    int[] a = {1, 2, 3, 12, 113, 14, 19, 20};
    ArrayList b = c.omitnum(a);
    for(int i = 0, n = b.size(); i < n; i++) {
      System.out.println(b.get(i));
    }
  }
}

Output:

Deleted: 14
Deleted: 19
1
2
3
12
113
20

Here is another way suggested by the user Abra , but I made some changes to preserve the default behaviour of printing

import java.util.Arrays;

public class Omit {
  static boolean printN(int n) {
    System.out.println("Deleted: " + Integer.toString(n));
    return false;
  }

  public static void main(String[] args) {
    int[] a = {1, 2, 3, 12, 113, 14, 19, 20};
    int[] b = Arrays.stream(a).filter(n -> n < 13 || n > 19 ||
      printN(n)).toArray();
    for(int i = 0;i < b.length; i++) {
      System.out.println(b[i]);
    }
  }
}

Output:

Deleted: 14
Deleted: 19
1
2
3
12
113
20

You should initialize an array before you are using it.

Else you can get NullPointerException .

Instead of this:

int[] arr = null;

You can use this:

int[] arr = new int[a.length];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM