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
You need to initialize your array like this, before :
Whenever you use an array, the JVM need to know it exists and its size.
In java there are many way to initialize arrays.
Just create an array with five emplacements. (You can’t add a sixth element)
Create an array with two emplacements and which contains the values 1 and 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.