0

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?

2
  • 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... Commented Nov 23, 2009 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> Commented Nov 23, 2009 at 21:43

1 Answer 1

10

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

Sign up to request clarification or add additional context in comments.

6 Comments

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?
If you don't want to fix the size, make it an array of Lists instead of a 2D-array.
@Student01: The only way around it is not using arrays. You can use a list of lists of strings.
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
ammoQ - you Can't make array of lists ( at least when using generics ). It's imposible to make an array of generic types
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.