Previous | Next | Trail Map | Writing Java Programs | The Nuts and Bolts of the Java Language


Arrays and Strings

Like other programming languages, Java allows you to collect and manage multiple values through an array object. Also, you manage data comprised of multiple characters through a String object.

Arrays

The character-counting example program declares an array (as a parameter to the main method) but never uses it. This section will show you what you need to know 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:

int[] arrayOfInts;
The int[] part of the declaration indicates that arrayOfInts 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 Objects, Classes, and Interfaces(in the Writing Java Programs trail) lesson. In particular look at Creating Objects(in the Writing Java Programs trail).

The following statement allocates enough memory for arrayOfInts to contain ten integer elements.

int[] arrayOfInts = new int[10]
In general, when creating an array, you use the new operator, plus the data type of the array elements, plus the number of elements desired enclosed within square brackets ('[' and ']').
elementType[] arrayName = new elementType[arraySize]
Now that some memory has been allocated for your array, you can assign values to its elements and retrieve those values:
for (int j = 0; j < arrayOfInts.length; j ++) {
    arrayOfInts[j] = j;
    System.out.println("[j] = " + arrayOfInts[j]);
}
As you can see from the example, to reference an array element, 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 one.

There's another interesting element (so to speak) in the small code sample above. The for loop iterates over each element of arrayOfInts, assigning values to its elements and printing out those values. Notice the use of arrayOfInts.length to retrieve the current length of the array. length is a property provided for all Java arrays.

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.

String[] arrayOfStrings = new String[10];
The elements in this array are reference types, that is, each element contains a reference to a String object. At this point, enough memory has been allocated to contain the String references, but no memory has been allocated for the Strings themselves. If you attempted to access one of arrayOfStrings elements at this point, you would get a NullPointerException because the array is empty and contains no Strings and no String objects. This is often a source of some confusion for programmers new to the Java language. You have to allocate the actual String objects separately:
for (int i = 0; i < arrayOfStrings.length; i ++) {
    arrayOfStrings[i] = new String("Hello " + i);
}

Strings

A sequence of character data is called a string and is implemented in the Java environment by the String(in the API reference documentation) class (a member of the java.lang package). The character-counting program uses Strings in two different places. The first is in the definition of the main method:
String[] args
This code explicitly declares an array named args that contains String 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 second use of String objects in the example program are these two uses of literal strings (a string of characters between double quotation marks):

"Input has "
    . . .
" chars."
The compiler implicitly allocates a String object when it encounters a literal string. So, the program implicitly allocates two 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. The java.lang package provides a different class, StringBuffer, which you can use to create and manipulate character data on the fly. The String and StringBuffer Classes(in the Writing Java Programs trail) is a complete lesson on the use of both Strings and StringBuffers.

String Concatenation

Java lets you concatenate strings together easily using the + operator. The example program uses this feature of the Java language to print its output. The following code snippet concatenates three strings together to produce its output:
"Input has " + count + " chars."
Two of the strings concatenated together are literal strings: "Input has " 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.


Previous | Next | Trail Map | Writing Java Programs | The Nuts and Bolts of the Java Language