Previous | Table of Contents | Next |
Simple variables that hold one value are useful, but are not sufficient for many applications. A program that plays a game of cards would want a number of Card objects it can manipulate as a whole. To meet this need, Java provides arrays.
An array is a collection of variables all of the same type. The components of an array are accessed by simple integer indices. In a card game, a Deck object might look like this:
class Deck { final int DECK_SIZE = 52; Card[] cards = new Card[DECK_SIZE}; public void print () { for (int I = 0; I < cards.length; I++) System.out.println(cards[i]); } }
First, we declare a constant called DECK_SIZE to define the number of cards in a deck. We declare a cards field as an array of type Card by following the type name in the declaration with brackets [ and ]. We initialize cards to a new array with DeckSize Card variables, initialized to null. An arrays length is fixed when it is created, and can never change.
The print method invocation shows how array components are accessed by enclosing the index of the desired element within brackets [ and ] following the array name.
You can probably tell from reading the code that array objects have a length field that says how many elements the array contains. The bounds of an array are integers between 0 and length-1. An IndexOutOfBoundsException is thrown if you use an index outside the bounds of the array.
The example also introduced a new variable declaration mechanismdeclaring the control variable of a for statement in its initialization clause. Declaring variables in the initialization section of a for loop is a concise and convenient way to declare simple loop variables. This construct is allowed only in the initialization of for statements; you cannot declare variables in the test clause of an if or while statement.
The loop variable i is available only within the code of the for statement. A loop variable declared in this manner disappears when the loop terminates, which means you can reuse that variable name in subsequent for statements.
Exercise 13.8
Modify the Fibonacci application to store the sequence into an array and print the list of values at the end.
Exercise 13.9
Modify the ImprovedFibonacci application to store its sequence in an array. Do this by creating a new class to hold both the value and a boolean value that says whether the value is even and then having an array of object references to objects of that class.
Java provides a String object type to deal specifically with sequences of character data, and provides language-level support for initializing them. The Java String class provides a variety of methods to operate on String objects.
Youve already seen String literals in examples like the HelloWorld program. When you write a statement like
System.out.println(Hello, world);
the Java compiler actually creates a String object initialized to the value of the specified string literal, and passes that String object as the parameter to the println method.
Unlike arrays, you dont need to specify the length of a String object when you create it. You can create a new String object and initialize it all in one statement, as shown in this example:
class StringsDemo { static public void main(String args[]) { String myName = Petronius; myName = myName + Arbiter; System.out.println(Name= + myName); } }
Here we create a String object reference called myName and initialize it with a String literal. Following initialization, we use the String concatenation + operator to make a new String object with a new value. Finally, we print the value of myName on the standard output stream. The output when you run the above program is
Name=Petronius Arbiter
In addition to the + sign as a concatenation operator, you can use the += operator as a shorthand for placing the variable name on the right-hand side of the assignment. Heres an upgraded version of the above example:
class BetterStringsDemo { static public void main(String args[]) { String myName = Petronius; String occupation = Reorganization Specialist; myName = myName = Arbiter; myName += ; myName += ( + occupation + ); System.out.println(Name = + myName); } }
Now, when you run the program you get this output:
Name = Petronius Arbiter (Reorganization Specialist)
String objects have a length method that returns the number of characters in the String. Characters are indexed from 0 through length() -1.
String objects are read-only, or immutable: The contents of a String never change. When you see statements like:
str = redwood; // ... do something with str .. str = oak;
the second assignment gives a new value to the object reference str, not to the contents of the string. Every time you perform operations that seem to modify a String object, such as += as used above, you end up with a new String object that is also read-only, while the original String objects contents remain unchanged. The StringBuffer class provides for mutable strings.
The equals method is the simplest way to compare two String objects to see if they have the same contents:
if (oneStr.equals(twoStr)) foundDuplicate(oneStr, twoStr);
Exercise 13.10
Modify the StringsDemo application to use different strings.
Previous | Table of Contents | Next |