1

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?

1

4 Answers 4

4

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

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

Comments

2

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)

Comments

0

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.

Comments

0

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).

Comments

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.