code_miner
code_miner

Reputation: 25

How to add an element in a null array in java?

I have created a function that takes an array and outputs another array. So I have declared the result array (which will be the output) as null cause the size varies and depends on the inputted array. (for eg. if I enter an array of integers and then I want to output the array containing even numbers from that array). So I will be using for or while loops and I want to know that how I can add the integer to that null array. I tried but I get a null pointer exception that says cannot store to int array cause "array" is null.

sorry but I can't use more advanced techniques cause I am new to java (I need to make this without using arraylist library as I am learning coding I found those type of questions which tries to make you perfect in i specific topic and then they take you to next step so u can be more prepared)

I am using this code and I want to know that add an element to my result array or should I initialized it as null or something else cause the size depends on inputted array in this code I am getting null pointer exception

public static int[] even(int[] numbers) {
    int[] result = null;

    int even = 0;
    int i = 0;
    int a = 0;
    while (i < numbers.length) {
        if (numbers[i] % 2 == 0) {
            even = numbers[i];
            result[a] = even;
            a++;
        }
        i++;
    }
    return result;
}

Upvotes: 0

Views: 1362

Answers (2)

code_miner
code_miner

Reputation: 25

public static int[] even(int[] numbers) {
    int[] result = null;

    int j = 0;
    int a = 0;
    while (i < numbers.length) {
        if (numbers[j] % 2 == 0) {
            a++;
        }
        j++;
    }
    result = new int[a];

    int even = 0;
    int i = 0;
    int b = 0;
    while (i < numbers.length) {
        if (numbers[i] % 2 == 0) {
            even = numbers[i];
            result[b] = even;
            b++;
        }
        i++;
    }
    return result;
}

Upvotes: 0

Phenomenal One
Phenomenal One

Reputation: 2587

The array's size needs to be initialized. If you want dynamic storage , read about List and Collection.

Here, if you still want to use array, you need the count.

int a = 0;
while (i < numbers.length) {
    if (numbers[i] % 2 == 0) {
        a++;
    }
    i++;
}

Then after this, you can initialize it as int[] result = new int[a];

Upvotes: 1

Related Questions