Java Reference
In-Depth Information
Note that the first output statement does not call the toString() method explicitly. The compiler inserts
the call for you to convert the StringBuffer object to a String object. This is necessary to make it
compatible with the + operator for String objects.
SUMMARY
You should now be thoroughly familiar with how to create and use arrays. Most people have little trouble
dealing with one-dimensional arrays, but arrays of arrays are a bit trickier so try to practice using these.
You have also acquired a good knowledge of what you can do with String objects, as well as
StringBuffer and StringBuilder objects. Most operations with these objects are very straightforward
and easy to understand. Being able to decide which methods you should apply to the solution of specific
problems is a skill that comes with a bit of practice.
EXERCISES
You can download the source code for the examples in the topic and the solutions to the following exer-
cises from www.wrox.com .
1. Create an array of String variables and initialize the array with the names of the months from
January to December. Create an array containing 12 random decimal values between 0.0 and 100.0.
Display the names of each month along with the corresponding decimal value. Calculate and display
the average of the 12 decimal values.
2. Write a program to create a rectangular array containing a multiplication table from 1 * 1 up to 12
* 12. Output the table as 13 columns with the numeric values right-aligned in the columns. (The first
line of output is the column headings, the first column with no heading, then the numbers 1 to 12 for
the remaining columns. The first item in each of the succeeding lines is the row heading, which ranges
from 1 to 12.)
3. Write a program that sets up a String variable containing a paragraph of text of your choice. Extract
the words from the text and sort them into alphabetical order. Display the sorted list of words. You
could use a simple sorting method called the bubble sort. To sort an array into ascending order the
process is as follows:
a. Starting with the first element in the array, compare successive elements (0 and 1, 1 and 2, 2 and
3, and so on).
b. If the first element of any pair is greater than the second, interchange the two elements.
c. Repeat the process for the whole array until no interchanges are necessary. The array elements are
now in ascending order.
4. Define an array of ten String elements each containing an arbitrary string of the form "month/
day/year" ; for example, "10/29/99" or "12/5/01" . Analyze each element in the array and output the
date represented in the form 29th October 1999.
5. Write a program that reverses the sequence of letters in each word of your chosen paragraph from
Exercise 3. For instance, "To be or not to be." becomes "oT eb ro ton ot eb."
Search WWH ::




Custom Search