vote up 0 vote down star

I am currently creating a java application in which I have a 2d array which I want to get some data into.

I am creating the 2d array as such

String[][] addressData;

and then when I am trying to put data in I am using reference the exact position in the 2d array I want to enter the data into e.g

addressData[0][0] = "String Data";

The program compiles yet when I run I get a NullPointerException error. Am I using the wrong method to enter data into this 2d array?

flag
Could you add more of your code? Not a whole huge blort of it, just a small example which compiles and shows the behavior you're discussing. Like "hello world", but with your String[][]. And remember your pre and code tags, please... – CPerkins Nov 23 at 21:28
ok that's it running in a simple helloworld app <pre> public class Main { public static void main(String[] args) { String[][] addressData = null; addressData[0][0] = "Helloworld"; System.out.println(addressData[0][0]); } } <code> – Student01 Nov 23 at 21:43
See Luno's answer. – CPerkins Nov 23 at 22:13

1 Answer

vote up 9 vote down check

String[][] addressData - this is just declaration, you have to create actual object String[][] addressData = new String[size][size];

Btw, There is no 2d arrays in java String[][] is an array of arrays of strings

link|flag
Thanks for the reply, when I set a size to the 2d array it will work yet I don't want a limit on the size of the 2d array. It could range for just a few piece of data to thousands so I don't want a limit or null values. Is there any way around this? – Student01 Nov 23 at 21:36
If you don't want to fix the size, make it an array of Lists instead of a 2D-array. – ammoQ Nov 23 at 21:39
@Student01: The only way around it is not using arrays. You can use a list of lists of strings. – sepp2k Nov 23 at 21:40
As I wrote, it's not 2d array but array of arrays. You have to give a size when creating an array, so you have to do: String[][] array = new String[Size][]; - it'll create an array of String[] type with length = size filled with nulls, but you can put arrays with different length into it, for example: array[0] = new String[10]; array[1] = new String[50]; etc – Luno Nov 23 at 21:41
ammoQ - you Can't make array of lists ( at least when using generics ). It's imposible to make an array of generic types – Luno Nov 23 at 21:41
show 1 more comment

Your Answer

Get an OpenID
or

Not the answer you're looking for? Browse other questions tagged or ask your own question.