views:

82

answers:

4

Hi,

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

+6  A: 

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.

Colin Hebert
A: 

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];
Carlos
+3  A: 

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
Klark
A: 

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

Adam