Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java Java Data Structures Organizing Data Arrays

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,775 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