Important Notice: Our web hosting provider recently started charging us for additional visits, which was unexpected. In response, we're seeking donations. Depending on the situation, we may explore different monetization options for our Community and Expert Contributors. It's crucial to provide more returns for their expertise and offer more Expert Validated Answers or AI Validated Answers. Learn more about our hosting issue here.

NullPointerExceptions with arrays of objects?

0
Posted

NullPointerExceptions with arrays of objects?

0

Ans : When you allocate an array of objects, each component of the array is initialized to null. The individual components of the array must still be initialized with a constructor or an assignment statement. For example, consider this statement: Integer[] scores = new Integer[10]; int m = scores[5].intValue(); // throws NullPointerException This creates an array called scores containing ten references to Integer objects. Then it tries to get the value of the fifth component. However, each of those references is initially set to null. Thus when you try to call a method on one of the components of the array or pass the component to a method that expects a non-null argument, a NullPointerException is thrown. To fix this, you need to initialize the components of the array, either with constructors or with assignment statements For example: Integer[] scores = new Integer[10]; for (int i = 0; i < scores.length; i++) scores[i] = new Integer(i); int m = scores[5].intValue(); You do not need t

Related Questions

What is your question?

*Sadly, we had to bring back ads too. Hopefully more targeted.

Experts123