问题描述:

I have a query about strings.

I'm declaring my string array as:

private static String[] name;

I'm then trying to add a string to it:

name[0] = temp // Where temp as another string

I am getting a nullpointer error with the above code. Am I initialising my string array correctly?

网友答案:

Looks like you've missed to write name = new String[CAPACITY]; somewhere

网友答案:

If you want to add dynamically elements to an Array of Strings I would recommend you to do

private static ArrayList<String> name = new ArrayList<String>();

and then use below to add Strings:

name.add(temp);

If you know the size that it will have, then you can create an array like this:

private static String[] name = new String[10]; //if it's going to have 10 elements (typo corrected)
网友答案:

The problem is you have not initialized your string array.

You can declare and initialize it this way:

private static String[] name = new String[4]; Where '4' is the size of your array.

or:

private static String[] name = {temp, temp2, temp3}; Where the temps are each individual item in the array.

网友答案:

At the point

private static String[] name;

in your code, 'name' is still null.

for an array of Strings you have to declare the (constant) number of strings you want to store.

int n = 10;
private static String[] name = new String[n];

You then cannot ever write more than n strings to your array.

If you want to have the number of strings dynamically, you have to use a Vector<String> or an ArrayList<String>. Both objects use the myStrings.add(String string)-method to add a string and you can access strings by calling myStrings.get(int position).

相关阅读:
Top