Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Arrays can hold reference types as well as primitive types. You create such an array in much the same way you create an array with primitive types. Here's a small program,ArrayOfStringsDemo
that creates an array containing three string objects then prints the strings in all lower case letters.This program creates and populates the array in a single statement. However, you can create an array without putting any elements in it. This brings us to a potential stumbling block, often encountered by new programmers, when using arrays that contain objects. Consider this line of code:public class ArrayOfStringsDemo { public static void main(String[] args) { String[] anArray = { "String One", "String Two", "String Three" }; for (int i = 0; i < anArray.length; i++) { System.out.println(anArray[i].toLowerCase()); } } }After this line of code is executed, the array calledString[] anArray = new String[5];anArray
exists and has enough room to hold 5 string objects. However, the array doesn't contain any strings yet. It is empty. The program must explicitly create strings and put them in the array. This might seem obvious, however, many beginners assume that the previous line of code creates the array and creates 5 empty strings in it. Thus they end up writing code like the following, which generates aNullPointerException
:The problem is more likely to occur when the array is created in a constructor or other initializer and then used somewhere else in the program.String[] anArray = new String[5]; for (int i = 0; i < anArray.length; i++) { // ERROR: the following line gives a runtime error System.out.println(anArray[i].toLowerCase()); }
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |