Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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