1

The test code below leads to a "null pointer deference" bug on a String Array(on line 6). This leads to a NullPointerException.

public class TestString {
public static void main (String args[]) {
String test [] = null;
for (int i =0; i < 5; i++) {
  String testName = "sony" + i;
  test [k] = testName;
}
}
}

-- How do I fix this? -- What is it that causes this bug?

Thanks, Sony

4 Answers 4

6

You need to initialize your array like this, before :

test = new String[5];

Whenever you use an array, the JVM need to know it exists and its size.

In java there are many way to initialize arrays.

test = new String[5];

Just create an array with five emplacements. (You can't add a sixth element)

test = new String[]{"1", "2"};

Create an array with two emplacements and which contains the values 1 and 2.

String[] test = {"1", "2"};

Create an array with two emplacements and which contains the values 1 and 2. But as you noticed it must be donne at the same time with array declaration.

In Java arrays are static, you specify a size when you create it, and you can't ever change it.

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

Comments

3

There are too many errors in your code. 1) What is k? 2) You need to initialize the test array first.

String test[] = new String[5]; // or any other number

Comments

0

You are not initializing your array. On the third row you set it to null and then on the sixth row you're trying to set a string to an array that does not exists. You can initialize the array like this:

String test [] = new String[5];

Comments

0

Change String test[] = null; to String test[] = new String[5]; an array must be initialized.

See: http://download.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html

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.