The Nuts and Bolts of the Java Language |
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 aString
object.Arrays
The character-counting example program declares an array (as a parameter to themain
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:
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 Objects, Classes, and Interfaces lesson. In particular look at Creating Objects.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]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.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.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); }Strings
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). The character-counting program usesString
s in two different places. The first is in the definition of themain
method: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 second use of
String
objects in the example program are these two uses of literal strings (a string of characters between double quotation marks):The compiler implicitly allocates a"Input has " . . . " chars."String
object when it encounters a literal string. So, the program implicitly allocates twoString
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 is a complete lesson on the use of bothString
s andStringBuffer
s.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:Two of the strings concatenated together are literal strings: ""Input has " + count + " chars."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.
The Nuts and Bolts of the Java Language |