|
|
Start of Tutorial > Start of Trail > Start of Lesson | Search |
Like other programming languages, Java allows you to collect and manage
multiple values through an array object. You manage data comprised of
multiple characters through a String object.
ThecountCharsmethod doesn't use an array, but theCountclass'smainmethod declares an array as a parameter tomain. This section shows you how to create and use arrays in your Java programs.As for other variables, before you can use an array you must first declare it. Again, like other variables, a declaration of an array has two primary components: the array's type and the array's name. An array's type includes the data type of the elements contained within the array. For example, the data type for an array that contained all integer elements is array of integers. You cannot have a generic array--the data type of its elements must be identified when the array is declared. Here's a declaration for an array of integers:
Theint[] arrayOfInts;int[]part of the declaration indicates thatarrayOfIntsis an array of integers. The declaration does not allocate any memory to contain the array elements.If your program attempted to assign or access any values to any elements of
arrayOfIntsbefore memory for it has been allocated the compiler will print an error like this one and refuse to compile your program.testing.java:64: Variable arrayOfInts may not have been initialized.To allocate memory for the elements of the array, you must instantiate the array. You do this using Java's
newoperator. (Actually, the steps you take to create an array are similar to the steps you take to create an object from a class: declaration, instantiation, and initialization. You can learn more about creating objects in the Creating Objectssection of the next lesson.
The following statement allocates enough memory for
arrayOfIntsto contain ten integer elements.In general, when creating an array, you use theint[] arrayOfInts = new int[10]newoperator, plus the data type of the array elements, plus the number of elements desired enclosed within square brackets ('[' and ']').Now that some memory has been allocated for your array, you can assign values to its elements and retrieve those values:elementType[] arrayName = new elementType[arraySize]This example shows that to reference an array element, you append square brackets to the array name. Between the square brackets indicate (either with a variable or some other expression) the index of the element you want to access. Note that in Java, array indices begin at 0 and end at the array length minus 1.for (int j = 0; j < arrayOfInts.length; j ++) { arrayOfInts[j] = j; System.out.println("[j] = " + arrayOfInts[j]); }There's another interesting element (so to speak) in the small code sample above. The
forloop iterates over each element ofarrayOfInts, assigning values to its elements and printing out those values. Notice the use ofarrayOfInts.lengthto retrieve the current length of the array.lengthis a property provided for all Java arrays.Let's look again at the
mainmethod that callscountChars. In particular note the use of theargsarray:The Java runtime allocates the space for the args array, soimport java.io.*; public class Count { // ... countChars method omitted ... public static void main(String[] args) throws Exception { if (args.length >= 1) countChars(new FileReader(args[0])); else System.err.println("Usage: Count filename"); } }maindoesn't have to bother with it. Themainmethod ensures that there's at least one element in theargsarray, and if there is, it uses the first element in the array (presumably the name of a file) to open aFileReader.Arrays can contain any legal Java data type including reference types such as objects or other arrays. For example, the following declares an array that can contain ten
Stringobjects.The elements in this array are reference types, that is, each element contains a reference to aString[] arrayOfStrings = new String[10];Stringobject. At this point, enough memory has been allocated to contain theStringreferences, but no memory has been allocated for theStrings themselves. If you attempted to access one ofarrayOfStringselements at this point, you would get aNullPointerExceptionbecause the array is empty and contains noStrings and noStringobjects. This is often a source of some confusion for programmers new to the Java language. You have to allocate the actualStringobjects separately:for (int i = 0; i < arrayOfStrings.length; i ++) { arrayOfStrings[i] = new String("Hello " + i); }
A sequence of character data is called a string and is implemented in the Java environment by theStringclass (a member of the
java.langpackage).Count'smainmethod usesStrings in its the declaration of theargsarray:This code explicitly declares an array namedString[] argsargsthat containsStringobjects. The empty brackets indicate that the length of the array is unknown at compilation time because the array is passed in at runtime.The
countCharsmethod also uses twoStrings both in the form of a literal string (a string of characters between double quotation marks):The program implicitly allocates two"Counted " . . . " chars."Stringobjects, one for each of the two literal strings shown previously.
Stringobjects are immutable--that is, they cannot be changed once they've been created. Thejava.langpackage provides a different class,StringBuffer, which you can use to create and manipulate character data on the fly. TheStringandStringBufferClassescovers thoroughly the use of both the
StringandStringBufferclasses.String Concatenation
Java lets you concatenate strings together easily using the+operator. ThecountCharsmethod uses this feature of the Java language to print its output. The following code snippet concatenates three strings together to produce its output:Two of the strings concatenated together are literal strings: ""Counted " + count + " chars."Counted" and "chars." The third string--the one in the middle--is actually an integer that first gets converted to a string and then is concatenated to the others.
|
|
Start of Tutorial > Start of Trail > Start of Lesson | Search |