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.
ThecountChars
method doesn't use an array, but theCount
class'smain
method 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 thatarrayOfInts
is 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
arrayOfInts
before 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
new
operator. (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 Objects section of the next lesson.The following statement allocates enough memory for
arrayOfInts
to contain ten integer elements.In general, when creating an array, you use theint[] arrayOfInts = new int[10]new
operator, 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
for
loop iterates over each element ofarrayOfInts
, assigning values to its elements and printing out those values. Notice the use ofarrayOfInts.length
to retrieve the current length of the array.length
is a property provided for all Java arrays.Let's look again at the
main
method that callscountChars
. In particular note the use of theargs
array: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"); } }main
doesn't have to bother with it. Themain
method ensures that there's at least one element in theargs
array, 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
String
objects.The elements in this array are reference types, that is, each element contains a reference to aString[] arrayOfStrings = new String[10];String
object. At this point, enough memory has been allocated to contain theString
references, but no memory has been allocated for theString
s themselves. If you attempted to access one ofarrayOfStrings
elements at this point, you would get aNullPointerException
because the array is empty and contains noString
s and noString
objects. This is often a source of some confusion for programmers new to the Java language. You have to allocate the actualString
objects 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 theString
class (a member of thejava.lang
package).Count
'smain
method usesString
s in its the declaration of theargs
array:This code explicitly declares an array namedString[] argsargs
that containsString
objects. The empty brackets indicate that the length of the array is unknown at compilation time because the array is passed in at runtime.The
countChars
method also uses twoString
s both in the form of a literal string (a string of characters between double quotation marks):The program implicitly allocates two"Counted " . . . " chars."String
objects, one for each of the two literal strings shown previously.
String
objects are immutable--that is, they cannot be changed once they've been created. Thejava.lang
package provides a different class,StringBuffer
, which you can use to create and manipulate character data on the fly. TheString
andStringBuffer
Classes covers thoroughly the use of both theString
andStringBuffer
classes.String Concatenation
Java lets you concatenate strings together easily using the+
operator. ThecountChars
method 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 |