简体   繁体   中英

null pointer exception string 2d array in java

public String[][] fetchData()
{
    String[][] data = null;
    int counter = 0;
    while (counter < 10){
        data[counter] = new String[] {"abc"};
        counter++;
    }
    return data;
}

Getting the error in this loop. Please let me know where i am wrong

You need to allocate memory to data.

String[][] data = new String[ROW][COLUMN].

Read this

String[][] data = null;

==> you have a null pointer exception when you try to write in data

You might do

String[][] data = new String[10][];

You get a NPE because you explicitly set data to null :

String[][] data = null;

You need to allocate the number of rows first:

String[][] data = new String[][NUMBER_OF_ROWS];
data[counter] = new String[] {"abc"};

Here you are putting "abc" to array, but why you're using array if it has only one cell?

data[counter] = new String("sample string");

would be enough. And ofc you need also to declare "data" as one-dimensional array.

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