I have been trying to create an array of a class containing two values, but when I try to apply a value to the array I get a NullPointerException.
public class ResultList { public String name; public Object value; }
public class Test { public static void main(String[] args){ ResultList[] boll = new ResultList[5]; boll[0].name = "iiii"; } }
Why am I getting this exception and how can I fix it?
What Causes NullPointerException. The NullPointerException occurs due to a situation in application code where an uninitialized object is attempted to be accessed or modified. Essentially, this means the object reference does not point anywhere and has a null value.
NullPointerException is thrown when a reference variable is accessed (or de-referenced) and is not pointing to any object. This error can be resolved by using a try-catch block or an if-else condition to check if a reference variable is null before dereferencing it.
How to avoid the NullPointerException? To avoid the NullPointerException, we must ensure that all the objects are initialized properly, before you use them. When we declare a reference variable, we must verify that object is not null, before we request a method or a field from the objects.
NullPointerException is thrown when an application attempts to use an object reference that has the null value. These include: Calling an instance method on the object referred by a null reference. Accessing or modifying an instance field of the object referred by a null reference.
You created the array but didn't put anything in it, so you have an array that contains 5 elements, all of which are null. You could add
boll[0] = new ResultList();
before the line where you set boll[0].name.
ResultList[] boll = new ResultList[5];
creates an array of size=5, but does not create the array elements.
You have to instantiate each element.
for(int i=0; i< boll.length;i++) boll[i] = new ResultList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With