Java Java Data Structures Organizing Data Arrays

lukej
lukej
34,219 Points

No NullPointerException in un-assigned array?

For some reason I can not reproduce the NullPointerException when looping through an array in which some elements are null. Does anyone know why?

public class ArrayCopy {
// System.arraycopy(Object src, int srcPox, Object dest, int destPos, int length)
// src - the source array.
// srcPos - starting position in the source array.
// dest - the destination array.
// destPos - starting position in the destination data.
// length - the number of array elements to be copied.

  public static void main(String[] args) {
    String[] fruits = {"cherries", "berries"};
    String[] fruitsExpanded = new String[10];
    fruitsExpanded[0] = "bananas";
    fruitsExpanded[1] = "melons";
    System.arraycopy(fruits, 0, fruitsExpanded, 2, 2);
    for (String fruit : fruitsExpanded) {
      System.out.println(fruit);
    }
  }
}

Result

bananas
melons
cherries
berries
null
null
null
null
null
null

No exceptions, no errors

1 Answer

Tyler B
Tyler B
5,771 Points

Having null(s) in an array is not a/the problem. NPEs are generated when you attempt to do something to the object with a null value itself. It's a little confusing because print seems like it meets the "doing something" criteria but for various reasons printing a null value just prints the word "null". Try this, in your loop print the string followed by it's .length(). This should produce the NPE you're looking for