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.The output from this program ispublic 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()); } } }string one string two string threeThis program creates and populates the array in a single statement by using an array initializer. The next program,
Note: If you are using JDK 5.0 or later, it is also possible to loop through an array using the enhanced for syntax:String[] anArray = {"String One","String Two","String Three"}; for (String s : anArray) { System.out.println(s.toLowerCase()); }The colon in the for loop should be read as "in". So this loop would be read as: "for each String s in anArray".ArrayOfIntegersDemo
, populates the array withInteger
objects. Notice that the program creates oneInteger
object and places it in the array during each iteration of the for loop:The output from this program ispublic class ArrayOfIntegersDemo { public static void main(String[] args) { Integer[] anArray = new Integer[10]; for (int i = 0; i < anArray.length; i++) { anArray[i] = new Integer(i); System.out.println(anArray[i]); } } }The following line of code taken from the0 1 2 3 4ArrayOfIntegersDemo
program creates 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. After the previous line of code is executed, the array calledInteger[] anArray = new Integer[5];anArray
exists and has enough room to hold five integer objects. However, the array doesn't contain any objects yet. It is empty. The program must explicitly create objects 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 five empty objects in it. Thus, they end up writing code like the following, which raises aNullPointerException
:This problem is most likely to occur when the array is created in a constructor or other initializer and then used somewhere else in the program.Integer[] anArray = new Integer[5]; for (int i = 0; i < anArray.length; i++) { //ERROR: the following line gives a runtime error System.out.println(anArray[i]); }
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.