I am working on some project in java.
Here I’m stuck at this problem and not able to figure out where I am going wrong.
I have made two classes: Test and Child.
When I run the code I am get a NullPointerException.
package com.test;
public class Test {
child newchild = new child();
public static void main(String[] args) {
new Test().method();
}
void method() {
String[] b;
b = newchild.main();
int i = 0;
while (i < b.length) {
System.out.println(b[i]);
}
}
}
package com.test;
public class child {
public String[] main() {
String[] a = null;
a[0] = "This";
a[1] = "is";
a[2] = "not";
a[3] = "working";
return a;
}
}
Here’s the problem:
You’re immediately trying to dereference
a, which is null, in order to set an element in it. You need to initialize the array:If you don’t know how many elements your collection should have before you start populating it (and often even if you do) I would suggest using a
Listof some sort. For example:Note that you have another problem here:
You’re never changing
i, so it will always be 0 – if you get into thewhileloop at all, you will never get out of it. You want something like this:Or better: