Loading...

ARRAYS and
STRINGS

Links for Arrays And Strings

Index

Array's

Strings

<— Advanced Object Concepts   Applets —>

Preview

Up to this point in your studies,you learned how to create objects,perform arithmetic methods, and control program flow through the use of loops. you also learned how Java can be made to "make decisions."

In the world of programming, however, you'll sometimes need to process more than one item or condition at a time. You cold simply repeat each method for each and every variable that we need to process, but that wouldn't be a very efficient way of programming, even for a small number of items.

In this study unit, you'll study the power of arrays. An array is an object that's simply a list of variables. For example, if you were to create a class of the type Cars, you might create an array that simply lists different brand names for cars. Each brand name is still a car, and each item on the list is still a string that represents and instance of Car. The difference now, however, is that you can use the same methods on each of the items within the array without ever needing to rewrite the method, which will save both time and memory.

You'll also look at strings in detail. Just like everything else in Java, a string is and object. Any primitive object type can be converted into a string, and any one string can be compared to any other string. Strings allow powerful comparison operations within programs, and allow the creation of multiple paths for the program to follow.

When you complete this study unit, you'll be able to


Declaring an Array

While completeing the first fourchapters in this text, you stored values in variables. In the early sections, you simply stored a value and used it. In chapter 4, you created loops that allowed you to "recycle" variables; that is, after createing a variable, you can assign a value, use the value, and then, in successive cycles through the loop, reuse the variable as it holds different values.

>There are times, however, when storing just one value in memory at a time does not fill your needs. For example, a sales manager who supersvises 20 empolyees might want to determine whether each employee has produces sales above or below the average amount. When you enter the first employee's sales figure into a program, you can't determine whether it is above or below average, because you don't know what the averae is until you have all 20 figures. Unfortunately, if you assign 20 sales figures to the same variable, when you assign the figure for the second employee, it replaces the figure for the first employee.

A possible soution is to create 20 separate employee sales variable, each with a unique name, so you can store all the sales until you can determine and average. A drawback to this method is that if you have 20 different variable names to be assigned values, then you need 20 separate assignment statements. If you have 20 different variable names, the the statement that calculates total sales will be something unwieldy like total = firstAmt + secontAmt + thirdAmt + .... This method might work for 20 salespeople, but what if you have 10,000 salespeople?

The best solution is to create and array. An array is a list of data items that all have the same type and the same name. You declare and array variable in the same way as you declare any scalar variable, but you insert a pair of square brackets after the type. For example, to declare an array of double values to hold sales figures for salespeople, you write double[] salesFigure;.

You also can declare and array variable by placing the square brackets after the array name, such as double salesfigure[];. This format is familar to C and C++ programmers, but the perferred format among Java programmers is to place the brackets following the variable type and before the variable name, as in double[] salesFigure;.

After you create an array variable, you still need to create the actual array. You use the same procedure to create an array that you use to create and object. Recall that when you create a class named Employee, you can declare an Employee object with a declaration such as Employee oneWorker;, but that declaration does not actually create the oneWorker object. You create the oneWorker object when you use the keyword new and the constructor method, as in oneWorker = new Employee();. Similarly, declaring an array and actually reserving memory space for it are two distinct processes. To reserve memory locations for 20 salesFigure objects, you delcare the array variable with double[] salesFigure;, and then you create the array with salesFigure = new double[20];. Just as with objects, you also can declare and create an array in one statement with double[] salesFigure = new double[20];.

Some other languages, such as COBAL, BASIC, and Visual Basic, use parentheses rather than brackets to refer to individual array elements. By using brackets, the creators of Java made it easier for you to dinstinguish arrays from methods.

The statement double[] salesFigure = new double[20]; reserves 20 memory locations for 20 salesfigures. You can distinguish each salesFigure from the others with a subscript. A subscript is an integer contained within square brackets that indicates one of the array's variables, or elements. In the Java programming language an array's elements are numbered beginning with zero, so you can legally use any any subscript from zero throug 19 when working wiht an array that has 20 elements. In other words, the first salesFigure array element is salesFigure[0] and the last salesfigure element is salesFigure[19].

It is common to forget that the first element in a array is element zero, especially if you know another programming language in which the first array element is element one. Making this mistake means you will be "off by one" in your use of any array.

To remember that array elemets begin with element zero, it might be helpful to think of the first array element as being "zero elements away from" the beginning of the array, the second element as being "one element away from the beginning of the aray, the second element as being "one element away from" the beginning of the array and so on.

When you work with any individual array element, you treat it no differently than you would treat a single variable of the same type. For example, to assign a value to the first salesfigure in an array,you use a simple assignement statement, such as salesFigure[0] = 21.00.00;. To print the last salesFigure in an array of 20, you write Systemout.println(salesfigure[19];.

Next, you will create a small array to see how arrays are used. The array will hold salaries for four chategories of employees.

To create a program that uses and array:
  1. Open a new text file in your text editor.
  2. Begin the class that will demonstrate array use by typeing the folowing class and main() header and their corresponding opening curly brackets:

    public class Demoarray
    {
        public static void main(String[] args)     {
  3. On a new line, declare and create an array that can hold four double values by typeing double[] salary = new double[4];.
  4. One by one, assign four values to the four salaray array elements by typeing the following:

    salary[0] = 5.25;
    salary[1] = 6.55;
    salary[2] = 10.25;
    salary[3] = 16.85;
  5. To confirm that the four values have been assigned, print the salaries, one by one, using the folowing code:

    System.out.println("Sallaries one by one are:");
    System.out.println(salary[0]);
    System.out.println(salary[1]);
    System.out.println(salary[2]);
    System.out.println(salary[3]);
  6. Add the two closing curly brackets that end the main() method and the DemoArray class.
  7. Save the program as DemoArray.java in the Chapter.05 foler on your Student Disk
  8. Compile and run the program. the program's output appears in 5-1.
See DemoArray.java

5-1 Output of the DemoArray program
wallen@wallen-desktop:~$ cd Desktop/Java/Chapter.05
wallen@wallen-desktop:~/Desktop/Java/Chapter.05$ java DemoArray
Salaries one by one are:
5.25
6.55
10.25
16.85
wallen@wallen-desktop:~/Desktop/Java/Chapter.05$

Initializing and Array

A variable that has a primitive type, such as int, holds a value. A variable with a reference type, such as an array, holds a memory address where a value is stored.

Array names actually represent computer memory addresses; that is, array names are references, as are all Java objects. When you declare an array name, no computer memory address is assigned to it. Instead, the array variable name has a special value null, or Unicode value '\u000'. When you declare int[] someNums;, the variable someNums has a value of null.

When you define someNums as int someNums = new int[10];, then someNums has an actual memory address value. Each element of someNums has a value of zero because someNums is a numeric array. By default, character array elements are assigned '\u0000'. Boolean array elements are atuomatically assigned false.

You already know how to assign a different value to a single element of an array, as in someNums[0] = 46;. You also can assign nondefault values to array elements upon creation. To initialize an array, you use a list of values separated by commas and enclosed within curly brackets. For example, if you want to create an array named tenMult and store the first six multiples of 10 witin the array, you can declare int tenMult[] = {10, 20, 30, 40, 50, 60}; . When you initialize an array by giving it values upon creation, you do not give the a size—the size will be assigned based on the number of values you place in the initializing list. Also, when you initialize and array, you do not need to use the keyword new; instead, new memory is assigned based on the length of the list of provided values.

In java, you do not usually use a semicolon after a closing curly bracket, for example, at the end of a method body. However, every statement in Java requires a semicolon, and an array initialization is a statement. Do not forget to type the semicolon after the closing bracket at the end of an array's initialization list.

Next, you will alter your Demoarray program to initialize the array of doubles, rather than declaring the array and assigning values later.

to initialize an array of doubles:
  1. Open the DemoArray.java file in your text editor, delete the statement taht declares the array of four doubles named salary double[] salary = new double[4];, and then replace it with the following initialization statement: double[] salary = {5.25, 6.55, 10.25, 16.85};.
  2. Delete the following four statements that individually assign the values to the array salary[0] = 5.25; salary[1] = 6.55; salary[2] = 10.25; salary[3] = 16.85;.
  3. Save, compile,and test the program. The output is the same as 5-1.

Revised DemoArray1.java

Using Subscripts with an Array

If you treat each array element as an individual entity, then there isn't much of an advantage to declaring an array over declaring individual scalar (primitive) variables, such as int, double, or char. The power of arrays becomes apparent when you begin to use subscripts that are variables rather than subscripts that are constant values.

For example, when you declare an array of five integers, such as int[] valArray = {2, 14, 35, 67, 85};, you often want to perform the same operaton on each array element. To increase each array element by three, for example, you can write the following:

valArray[0] += 3;
valArray[1] += 3;
valArray[2] += 3;
valArray[3] += 3;
valArray[4] += 3;
;

With five array elements, this task is manageable. However, you can shorten the task by using a variable as the subscript. Then you can use a loop to perform arithmetic on each array element in the array, as in the following example:

for(sub = 0; sub < 5; ++sub)
    valArray[sub] +=3;

The variable sub is set to zero, and then it is compared to five. Because the value is less than five, the loop executes and three is added to valArray[0]. Then the variable sub is incremented and it becomes one, which is still less than five, so when the loop executes again, valArray[1] is increased by three, and so no. A process that took five statements now takes only one. Additionally, if the array had 100 elements, the first method of increasing the array values by three would result in 95 additional statements. the only change required in the for loop woud be to compare sub to 100 instead of to five.

Next, you will modify the DemoArray program to use a for loop with the array.

To use a for loop with the array in DemoArray:
  1. Open the DemoArray.java file in your text editor, and then delete the four println() statements that print the four array values and replace them with the following for loop:

    for(int x = 0; x < 4; ++x)
        System.out.println(salary[x]);
  2. Save, compile, and run the program. Again, the output is the same as 5-1

DemoArray2 printing done with for loop

Declaring an Array of Objects

Just as you can declare arrays of integers or doubles, you can declare arrays that hold elements of any type, including objects. For example, assume you created the Employee class shown in 5-2. This class has two data fields (emmpNum and empSalary), a constructor, and a get mehtod for each field

5-2 A simple employee class
public class Employee

{

   private int empNum;

   private double empSalary;

   Employee(int num, double sal)

   {

      empNum = num;

      empSalary = sal;

   }

   public int getEmpNum()

   {

      return empNum;

   }

   public double getSalary()

   {

   return empSalary"

   }

}

You can create separate Employee objects with unique names, suchs as Employee painter, electrician, plumber;, but for many programs it is far more convenient to create and array of employees. An array named emp that holds seven Employees is defined as Employee[] emp = new Employee[7];. This statement reserves enough computer memory for seven Employee objects named emp[0] through emp[6]. However, the statement does on actually construct those employee objects; instead, you must call the seven individual constructors. According to the class defination shown in 5-2, the Employee constructor requires two arguments. an employee number and a salary. If you want to number your Employees 101, 102, 103, and so on, and start each Employee at a salary of $5.35, then the loop that constructs seven Employee objects is as follows:

for(x = 0; x < 7; ++x)
    emp[x] = new Employee(101 + x, 5.35);

As x varies from 0 through 6, each of the seven emp objects is constructed with an employee number that is 101 more than x, and each of the seven emp objects holds the same salary of 5.35.

To use a method that belongs to an object that is part of an array, you insert the appropriate subscript notation after the array name and before the dot that precedes the method name. For example, to print data for seven employes stored in the emp array, you can write the following;

for(x = 0; x < 7; ++x)
    System.out.println(emp[x].getEmpNum() + " " + emp[x].getSalary();

Pay attention to the syntax of the Employee objects` method calls, such as emp[x].getEmpNum(). Although you might be tempted to place the subscript at the end of the expresson after the method name, as emp.getEmpNum[x], you cannot do so—the values in x (0 through6) refer to a particular emp, each of which has access to a single get getEmpNum() method. The placement of the brackeded subscript following emp means the method "belongs" to a particular emp.

Next, you will create an array of Event objects for Event Handlers Incorporated.

To create an array of Event objects:
  1. Open the Event.java file from the Chapter.05 folder on your Student Disk. This program is the same one that you created in Chapter 4. Examine the code so that you recall that the class contains two data fields: a character representing the type of event, and a double representing the minimum that is charged for the event. The constructor requires values for the two data fields. The class also contains methods to get the field values.
    see Event.java
  2. Open a new text file in your text editor and create an EventArray program. Type the following class header, the main() method header, and their opening curly brackets:

    public class EventArray
    {
        public static void main(String[] args)     {
  3. Declare an array of five Event objects using the following code. You will also declare an integer that can be used as a subscript.

    Event[] someEvents = new Event[5];
    int x;
  4. Enter the following for loop that calls the Event constructor five times ,making each event type 'X' with a minimum charge of 0.0:

    for(x = 0; x < 5; ++ x)
        someEvents[x] = new Event('X',0.0);
  5. To confirm that the Event objects have been created, print their values by typeing the following:

    for(x = 0; x < 5; ++x)
        System.out.println(someEvent[x].getEventType() + " " + someEvents[x].getEventMinRate());
  6. Add the two curly brackets that end the main() method and the class defination.
  7. Save the program as EventArray.java in the Chapter.05 folder. Compile and run the program. 5-3 shows the output.
see this step in EventArray.java
wallen@wallen-desktop:~$ cd Desktop/Java/Chapter.05
wallen@wallen-desktop:~/Desktop/Java/Chapter.05$ javac EventArray.java
wallen@wallen-desktop:~/Desktop/Java/Chapter.05$ java EventArray
X 0.0
X 0.0
X 0.0
X 0.0
X 0.0
wallen@wallen-desktop:~/Desktop/Java/Chapter.05$

An array of five event objects—each of which has the same event type and fee—is not very interesting or useful. Next, you will modify the Eventarray program so that it create the events interactively and so each event will possess unique properties.

To create an interactive EventArray program:
  1. Open the EventArray.java file in your text editor, positon the cursor to the right of the opening curly bracket of the EvenArray class, press the Enter key, and then type the following statements to declare three constants for the corporate, private, and non-profit event rates.

    static final double CORP_RATE = 75.99;
    static final double PRI_RATE = 47.99;
    static final double NON_PROF_RATE = 40.99;
  2. The program will accept keyboard input, so positon the cursor to the right of the main() method header and then type throws Exception.
  3. Just before the for statement that constructs five events, add the following two new variables that will hold an event type and rate and initialize them with dummy values:

    char event = 'Z';
    double rate = 0;
  4. Within the for loop, remove the line that constructs events with type 'X' and fee 0.0 (someEvents[x] = new Event('X',0.0);), and then replace the line with the following block that prompts the user for one of three event types and constructs an appropriate event based on the value entered:

    {    System.out.println("Enter event type");
       System.out.println("C for corporate");
       System.out.println("P for private");
       System.out.println("N for non-profit");
       event = (char)System.in.read();
       System.in.read(); //Absorbs Enter key
       if(event == 'C')
          rate = CORP_RATE;
       else if(event == 'P')
          rate = PRI_RATE;
       else rate = NON_PROF_RATE;
       someEvent[x] = new Event(event, rate);
    }
  5. Change the body of the last for loop as follows so it prints and event number along wiht the event information:

    System.out.println("Event " + (x + 1) + " " + someEvents[x].getEventType() + " " + someEvents[x].getEventMinRate());
  6. At this point, when you run the program, if you enter and event type that is not C or {, the program will assume that the rate is the non-profit rate by default.
  7. Save, compile, and run the program several times. confirm that no matter what combination of C, P, and N you use for data entry, the list of events is stored and displayed correctly.
public class EventArray
{
Declares 3 constants
static final double CORP_RATE = 75.99;
static final double PRI_RATE = 47.99;
static final double NON_PROF_RATE = 40.99;
    program accepts input
   public static void main(String[] args) throws Exception
   {
   Event[] someEvents = new Event[5];
   int x;
    // two new variables that will hold an event type and rate and initialize them with dummy values:
   char event = 'Z';
   double rate = 0;
    prompts user for 1 of 3 event types 5 times
   for(x = 0; x < 5; ++x)
      {
         System.out.println("Enter event type");
         System.out.println("C for corporate");
         System.out.println("P for private");
         System.out.println("N for non-profit");
         event = (char)System.in.read();
         System.in.read(); // Absorbs enter key
          // constructs appropriate event
         if(event == 'C')
            rate = CORP_RATE;
         else if(event == 'P')
            rate = PRI_RATE;
         else rate = NON_PROF_RATE;
         someEvents[x] = new Event(event, rate);
      }
   for(x = 0; x < 5; ++x)
      System.out.println(someEvents[x].getEventType() + " " + someEvents[x].getEventMinRate());
   }
}
wallen@wallen-desktop:~$ cd Desktop/Java/Chapter.05
wallen@wallen-desktop:~/Desktop/Java/Chapter.05$ java EventArray
Enter event type
C for corporate
P for private
N for non-profit
C
Enter event type
C for corporate
P for private
N for non-profit
P
Enter event type
C for corporate
P for private
N for non-profit
N
Enter event type
C for corporate
P for private
N for non-profit
C
Enter event type
C for corporate
P for private
N for non-profit
P
C 75.99
P 47.99
N 40.99
C 75.99
P 47.99
wallen@wallen-desktop:~/Desktop/Java/Chapter.05$

Searching an Array for an Exact Match

When you want to determine whether some varaiable holds one of many values, one option is to use a series of if statements to compare the variable to a series of valid values. For example, suppose that a company manufactures 10 items. When a customer places and order for an item, you need to determine whether the item number on the order form is valid. If valid item numbers are sequential, such as 101 through 110, then the following if statement that uses a logical AND can verify the order number and set a boolean field to be true: if(itemOrdered >= 101 && itemOrdered <= 110) validItem = true;. If the valid item numbers are nonsequentilal, however— for example, 101, 108, 201, 213, 266, 304, and so on— you must code the following deeply nested if statement or a lengthy OR comparison to determine the validity of an item number:

if(itemOrdered == 101)
    validItem = true;
else if(itemOrdered == 108)
    validItem = true;
else if(itemOrdered == 201)
    validItem = true;
// and so on

Instead of a long series of if statements, a more elegant solution is to compare the itemOrdered variable to a list of values in an array. You can initialize the array with the valid values with the following statement:

int[] validValues = {101, 108, 201, 213, 266, 304, 311, 409, 411, 412};

Then, you can use a for statement to loop through the array, and set a bookean variable to true when a match is found:

for(int x=0; x <10; ++x)
{
    if(itemOrdered == validValues[x])
        validItem = true;
}

This simple for loop replaces a long series of if statements. Also, if a company carries 1,000 items instead of 10, then the only part of the for statement that changes is the comparison in the middle. As an added bonus,if you set up another parallel array with the same number of elements and corresponding data, you can use the same subscript to access additional information. For example, if the 10 items your company carries have 10 different prices, then you can set up any array to hold those prices: double[] prices = {0.89, 1.23, 3.50, 0.67 ... };. The prices must appear in the same order as their correspondingitem numbers in the validValues array. Now the same for loop that finds the valid item number also finds the price, as shown in 5-4. in other words, if the item number is found in the second position in the validValues array, then you can find the correct price in the second position in the prices array.

If you initialize parallel arrays,it is convenient to use spacing so that the values that correspond to each other visually align on the screen or printed page.

5-4 Accessing information in parallel arrays
int[] validValues = {101,  108,  201,  213,  266,

                     304,  311,  409,   411, 412};

double[] prices =   {0.89, 1.23, 3.50, 0.69, 5.79,

                     3.19, 0.99, 0.89, 1.26, 8.00};

for(inx x = 0; x < 10; ++x)

{

   if(itemOrdered == validValues[x])

   {

      validItem = true;

      itemPrice = prices[x];

   }

}
In an array with many possible matches, it is most efficient to place the most common items first, so that they are matched right away. For example, if item 311 is the most often ordered item, place 311 first in the valid Values array, and its price ($0.99) first in the prices array

Within the code shown in 5-4, you compare every itemOrered with each of the 10 validValues. Even when an itemOrdered is equivalent to the first value in the validValues array (101), you always make nine additional cycles through the array. On each of thes nine additional cycles, the comparison between itemOrdered and validValues[x] is always false. As soon as a match for an itemOrdered is found, it is most efficeint to breakout of the for loop early. An easy way to accompish this is to set x to a high value within the block of statements executed when there is a match. Then, after a match, the for loop will not execute again because the limiting comparison (x < 10) will have been surpassed. 5-5 shows this program.

5-5 Breaking out of a for loop early
for(x = 0; x < 10; ++x)

{

   if(itemOrdered == validValues[x])

   {

      validItem = true;

      itemPrice = prices[x];

      x = 10; // Break out of loop when you find a match

   }

}
Instead of the statement that sets x to 10 when a match is found, you could place a break; statement within the loop in its place.
Some programmers disapprove of breaking out of a for loop early, whether you do it by setting a variale's value or by using a break; statement. if you (or your instructor) agree with this philosophy, then use a method that uses a while statement as described next.

As an alternative, you can choose to forgo the for loop entirely, and use while loop to search for a match. Using this approach, you set a subscript to zero and while the itemOrdered is not equal to a value in the array, you increase the subscript and keep looking. You search only while the subscript remains lower than the number of elements in the array. If the subscript inceases to 10, then you never found a match in the 10-element array. If the loop ends before the subscript reaches 10, then you found a match and the correct price can be assigned to the itemPrice variable. 5-6 shows this programming approach.

5-6 Searching wiht a while loop
x = 0;

while(x < 10 && itemOrdred != validvalues[x])    ++x;

if(x !=10)

{

   validItem = true;

   itemPrice = prices[x];

}

Next, you will delete the if that determine a price for each event at Event Handlers Incorporated and replace them with an array search.

To determine event pricing using parallel arrays:
  1. Open the EventArray.java file in your text editor, position the cursor to the right of the statement that declares the rate variable (double rate;), and press the Enter to start a new line of text. Then type the following character array to hold the code for the three allowed event types:
    char[] eventCode = {'C', 'P', 'N'};
  2. Press the Enter key, and then on the next line, add the following code to create a double array to hold the rates charged for the three event types:

    double[] eventRate = {CORP_RATE, PRI_RATE, NON_PROF_RATE};
  3. Notice that you can use symbolic constants as well as literal constants as array elements. You could even combine the two types of constants witin the same array. You can even use variable names as array elements. Don't forget, however, that all elements within a single array must have the same type.
  4. Remove the five lines of code (beginning with if(event == 'C')...) that constitute the if...else structure that determeines the event rate. This if structure is no longer needed. Replace it with the following for loop that searches through the eventCode array, and upon finding a match, selects a price from the eventRate array:

    for(int i=0; i < 3; ++i)
    {
        if(event == eventCode[i])
            rate = eventRate[i];
    }
  5. Save, compile,and run the program. confirm that, just as before, no matter what combination of C,P,and N you use for data entry, the list of events is stored and displayed correctly

see EventArray with event pricing using parallel arrays:

When you run the program, if you enter an invalid event code, and event object is created and and incorrect rate is assigned to the event object. Now that you have an array of valid event codes,it is a simple matter to disallow any invalid event codes (those other than C,P, or N).

To force all five Event objects to contain valid codes and rates:
  1. Within the EventArray.java program, positon the cursor to the right of the double rate = 0; variable declaration, press the Enter key to start a new line, and then enter the following code to create a boolean variable named codeIsValid: boolean codeISValid;.
  2. Position the cursor at the beginning of the for statement that begins the search through the eventCode array ( for(int i - 0;...)), and then press the Enter key to start a new line. Just before the for loop, you need to ensure that the codeIsValid variable is set to false by typing codeIsValid = false;.
  3. Within the for loop, change the if statement that checks the eventCode array as follows so that if the event variable is equivalent to one of the eventCodes, then a block of two statements will execute—besides seting the rate, the block sets the codeIsValid variable to true:

    if(event == eventCode[i])
    {
        rate = eventRate[i];
        codeIsValid = true;
    }
    You can make the program more efficient by breaking out of the for loop early when an event matches and eventCode array element. Set the loop control variable i to a high value when a match is found.
  4. Place the cursor to the right of codeIsValid = true; and then press the Enter key to start a new line. Type i = 3; on the new line.
  5. Position the cursor at the beginning of the statement that constructs one of the five someEvents objects (someEvents[x] = new Event(event,rate);). Press the Enter key to start a new line and insert the following condition so the object is created only if the code is valid: if(codeIsValid). To show clearly that the assignment statement depends upon the if, insert two spaces at the beginning of the line someEvents[x] = newEvent(event, rate);.
  6. Position the cursor just after someEvents[x] = new Event(event, rate); then press the Enter key to start a new line. Enter the following else clause that reduces x. Now, for example, if a code is not valid on the third pass through the loop when x is 2, x will be decremented to 1. At the top of the for loop (in third section within the parentheses), x is increased to 2 again for the next pass through the for loop. So if the user enters a vaild code during this fourth execution of the loop, x still be 2, and an object will correctly be created at someEvent[2].

    else
      --x;
  7. Save, compile,and run the program. Enter as many vaild and invalid codes as you like.l After five of the codes yu enter are identified as valid, the five constructed objects will display.

See this polished EventArray.java

Searching an Array for a Range Match

searching an array for an exact match is not always practical. For example, supose your company gives customer discounts based on the quanity of items orderred. Perhaps no discount is give for any order of fewer than a dozen items, but there are increasing discounts available for orders of increasing quanities, as shown in 5-7

5-7 Discount table for an imaginary company
Total Quanity OrderedDiscount
1 to 12none
13 to 49 10%
50 to 99 14%
100 to 19918%
200 or more20%

One awkward option is to create a single array to store the discount rates. You could use a variable named numOfItems as a subscript to the array, but the array would need hundreds of entries—for example, double[] discount = {0,0,0,0,0,0,0,0,0,0,0,0,0, .10, .10 ...};. When numOfItems is 3, for example, then discount[numOfItems] or discount[3] is 0. When numOfItems is 14, then discount[numOfItems] or discount[14] is .10. Becaues a customer might order thousands of items, the array would need to be ridiculously large.

Notice that there are 13 zeros listed in discount array in the preceding example. the first array element has a zero subscript (and a zero discount for zero items). The next 12 discounts (1 through 12 items) are also discounts of zero.

A better option is to create parallel arrays. One array will hold the five discount rates, and the other array will hold five discount range limits. The Total Quanity Ordered column in 5-7 shows five ranges. If you use only the first figure in each range, you can create an array that holds five low limits: int[] discountRangeLimit = {1, 13, 50, 100, 200};. A parallel array will hold the five discount rates: double[] discount = {0, .10, .14, .18, .20};. Then, starting the the last discountRangeLimit array element, for any numOfItems greater than or equal to discountRangeLimit[4], the appropriate discount is discount[4]. In other words,for any numOfItems less than discountRangeLimit[4], you should decrement the subscript and look in a lower range. 5-8 shows the code

5-8: Searching an array of ranges
int[] discountRangeLimit = {1,  13,  50,  10, 200};

double[] discount =        {0, .10, .14, .18, .20};

int sub = 4;

while(sub >=0 && numOfItems < discountRangeLimit[sub])

    --sub;

customerDiscount = discount[sub];
Making sure that the subscript does not fall below zero in the statement while(sub >= 0 && numOfItems < discountRangeLimit[sub]) is a good programming practice. Although this would happen only if a numOfItems held a negative value, such a check will prevent a program error.

Passing Arrays to Methods

You already have seen that you can use any individual array element in the same manner as you would use any single variable of the same type. That is, if you declare and interger array as int[] someNums = new int[12];, then you can subsequently print someNums[0] or add one to someNums[1], just as you would for any integer. Similarly, you can pass a single array element to a method in exactly the same manner as you would pass a variable.

Examine the program shown in 5-9. The program creates an array of four intergers and prints them. Then the program calls a method, methodGetsOneInt(), four times, passing each element in turn. The method prints the number, changes the number to 999, and then prints the number again. finally, back in main(), the four numbers are printed again.

5-9 PassArrayElement program
public class PassArrayElement

{

   public static void main(String[] args)

   {

      int[] someNums = {5, 10, 15, 20};

      int x;

      for(x=0; x < 4; ++x)

         System.out.println("In main " + someNums[x]);

         for(x = 0; x < 4; ++x)

         methodGetsOneInt(someNums[x]);

      for(x = 0; x < 4; ++x)

         system.out.println("At end of main " + someNums[x]);

      }

   Public static void methodGetsOneInt(int one)

   {

      System.out.println("In methodGetsOneInt " + one);

      one = 999;

      System.out.println("After change " + one);

   }

}

5-10: Output of the PassArrayElement program
wallen@wallen-desktop:~/Desktop/Java/Chapter.05$ java PassArrayElement
In main 5
In main 10
In main 15
In main 20
In methodGetsOneInt 5
After change 999
In methodGetsOneInt 10
After change 999
In methodGetsOneInt 15
After change 999
In methodGetsOneInt 20
After change 999
At the end of main 5
At the end of main 10
At the end of main 15
At the end of main 20
wallen@wallen-desktop:~/Desktop/Java/Chapter.05$

As you can see from 5-10, the four numbers that were changed in the methodGestOneInt() method remain unchanged back in main(). the variable named on is local to the methodgestOneInt() method, and any changes to variables passed into the method are not permanent and are not reflected in the array in the main() program. Each variable named one in the methodGetsOneInt() method holds only a copy of the array element passed into the method.

The outcome is quite different whne you pass an entire array to a method. Arrays, like all objects, are passed by reference, which, as you will recal from Chapter 3, means that the method receives the actual memory address of the array and has access to the actual values in the array elements. The program shown in 5-11 creates and array of four integers. After the integers print, the entire array is passed to a method named methodGetsArray(). Within the method, the numbers print, which shows that they retain their values from main(), but then the value 888 is assigned to each number. Even though the methodGetsarray() method is a void method (meaning nothing is returned to the main() method), when the program prints the array for the second time within main(), all of the values have been changed to 888, as you can see in 5-12. Because arrays are passed by reference, the methodGetArray() method "knows" the address of the array declared in main() and makes it changes directly to the original array that was declared in the main() method.

5-11PassArray program
public class PassArray

{

   public static void main(String[] args) throws Exception

   {

      int[] someNums = {5, 10, 15, 20};

      int x;

      for(x = 0; x < 4; ++x)

         System.out.println("in main " + someNums[x];

      methodGetsArray(someNums);

      for(x = 0; x < 4; ++x)

         System.out.println("At end of main " + someNums[x]);

   }

   public static void methodGetsArray(int[] arr)

   {

      for(int y = 0; y < 4; ++y)

      {

         System.out.println("In methodGetsArray " + arr[y]);

         arr[y] = 888;

      }

   }

}


5-12 Output of the PassArray program
wallen@wallen-desktop:~$ cd Desktop/Java/Chapter.05
wallen@wallen-desktop:~/Desktop/Java/Chapter.05$ java PassArray
in main 5
in main 10
in main 15
in main 20
In methodGetsArray 5
In methodGetsArray 10
In methodGetsArray 15
In methodGetsArray 20
At end of main 888
At end of main 888
At end of main 888
At end of main 888
wallen@wallen-desktop:~/Desktop/Java/Chapter.05$

Next, you will add a new method to the Event object class type. Then you will add steps to the EventArray program so you can pass an array of Event objects to a method. This program will demonstrate that changes made within the method affect values in the array permanently.

To add a new method to the Event Class:
  1. In your text editor, open the Event.java file from the Chapter.05 folder on your Student disk. This text file contains the class defination for Event Objects.
  2. Add a new setEventMinRate() method that you can use to alter an Event object's eventMinRate. Position the cursor to the left of the final closing curly bracket for the Event class, and then press the Enter key to start a new line above the closing bracket. Then enter the following setEventMinRate() method:

    public void setEventMinRate(double rate)
    {
        eventMinRate = rate;
    }
  3. Save the Event.java file, and then compile it from the command line using the command javac Event.java.

See revised Event.java

Next,you will add a method call and a method to the EventArray program. The method will receive an array of Event objects and increase the rate for each event by $5.00.

To add a new method to the EventArray program:
  1. Open the EventArray.java file in your text editor, position the cursor to the left of the closing curly bracket for the main() method in the EventArray class, and then press the Enter to insert a new blank line above the closing curly bracket.
  2. Enter the following method call to a raiseRates() method, which will reeive the someEvents array and raise each Event's rate by $5.00:
    raiseRates(someEvents);.
  3. Press the Enter key. To demonstrate that the rates changed as a result of the raiseRates() method, add the following print loop on the new line.
    If you do not want to type this statement, you can simply use your editor's copy function to copy the identical statement that already exists within the program.


    for(x = 0; x <5; ++x)
       System.out.println("Event " + (x + 1) + " " +
          someEvents[x].getEventType()+ " " + someEvents[x].getEventMinRate());
  4. Place the cursor to the right of the main() method's closing curly bracket, and then press the Enter key to start a new blank line before the closing bracket for the EventArray program. Then enter the following raiseRates() method. The method loops through the array five times. With each iteration, the method gets the array element's current rate, stores it in a temporary double variable, and adds $5.00 to the temporary variable. Then the temporary variable value is assigned back into the array object's rate with the setEventMinRate() method.

    private static void raiseRates(Event[] evnt)
    {
       double temp;
       for(int q = 0; q < 5; ++q)
       {
          temp = evnt[q].getEventMinRate();
          temp += 5;
          evnt[q].setEventMinRate(temp);
       }
    }
    You can replace the three statements temp = evnt[q].getEventMinRate();, temp +=5;, and evnt[q].setEventMinRate(temp); with one statement: event[q].setEventMinRate(evnt[q].
    getEventMinRate() + 5);
    . If this method call within a method call is clear to you, feel free to use it.
  5. Save the program, and then compile and run it. After you answer the prompts to create five events, their old rates and the new increased rates should display on the screen.

EventArray program with the raiseRates() method

Using the Array Length

Every array object that you create is automatically assigned a data field named length. The length field contains the number of elements in the array. For example, when you declare double[] salaries = new double[8];, the field salaries.length is assigned the value 8.

When you work with array elements, you must ensure that the subscript you use remains in the range zero through length -1. To access all eight elements of a salaries array, for example, you can code the number 8 explicitly, as in for(x = 0; x <8; ++x)... If you modify your program to hold more or fewer array elements, you must remember to change every appropriate reference to the array size within the program. Many text editors have a "find and replace" feature that lets you change all the 8s, but you must be careful not to change any 8s that have nothing to do with the array. A better technique is to use salaries.length, as in for(x = 0; x < salaries.length; ++x)... That way, if you change the size of the salaries array, then the array always will use the correct maximum length.

Next, you will remove the explicit 5 you have used in each for lop within the EventArray program, and replace each with a reference to the length field.

To use the array length field:
  1. Locate the first for statement in the main() method of your EventArray program. This loop constructs five Event Objects. Delete the 5 in the for expression and then replace that number with someEvents.length.
  2. Locate the next for loop in the EventArray program, which checks the event codes entered by a user. Delete the 3 from the forloop and replace that number with eventCode.length.
  3. Locate the next for loop, which prints array values. Delete the 5 in the for loop and replace that number with someEvents.length.
  4. Within the raiseRates() method, locate the for loop that raises the rate of each array element. Withing the raisRates() method, the array name is evnt. Replace the 5 in this for loop with evnt.length.
  5. Save, compile, and run the program. The executon of the program should be the same as it was before—five objects are created and three valid event codes are checked.

EventArray.java using the array length field

SUMMARY

Questions

  1. A list of variables that all have the same type and same name is a(n) ____________.
    1. register
    2. array
    3. list
    4. index
  2. When you declare an array variable, you must insert _________ after the type.
    1. a pair of square brackets
    2. a pair of parentheses
    3. a pair of curly brackets
    4. the keywork array
  3. You reserve memory locations for an array when you __________.
    1. declare an array name
    2. use the keywork new
    3. use the keywork mem
    4. explicitly store value within the array elements
  4. The statement int[] value = new int[34]; reserves memory for ____________ integers.
    1. 0
    2. 33
    3. 34
    4. 35
  5. An integer contained within square brackets that indicates one of an array's variables is a(n) _______________.
    1. pointer
    2. parameter
    3. argument
    4. subscript
  6. If you declare an array as int[] num = new int[6];, the first elemnt of the array is ______________.
    1. num[0]
    2. num[1]
    3. num[]
    4. impossible to tell
  7. If you declare an array as int[] num = new int[6];, the last element of the array is ___________.
    1. num[5]
    2. num[6]
    3. num[7]
    4. impossible to tell
  8. Array names are _______________.
    1. values
    2. functions
    3. references
    4. allusions
  9. Unicode value '\u0000' also is known as _____________.
    1. nill
    2. void
    3. nada
    4. null
  10. When you initialize an array by giving it values upon creation, you __________.
    1. do not give the array a size
    2. also must give the array a size
    3. must make all the values zero, blank, or false
    4. must make sure each value is different from the others
  11. Assume an array is declared as int[] num = new int[4];. Which of the following statements correctly assigns the value 100 to each of the four array elements?
    1. for(x = 0; x < 3; ++x) num[x] = 100;
    2. for(x = 0; x < 4; ++x) num[x] = 100;
    3. for(x = 1; x < 4; ++x) num[x] = 100;
    4. for(x = 1; x < 5; ++x) num[x] = 100;
  12. If a class named Student contains a method setID() that takes an integer argument, and you create an array of 20 Student objects named scholar, which of the following statements correctly assigns and ID number to the first Student scholar?
    1. Student[0].setID(1234);
    2. scholar[0].setID(1234);
    3. Student.setID[0](1234);
    4. scholar.setID[0](1234);
  13. Assuming char[] goodResponses = {'Y', 'y', 'N', 'n'};, which of the following statements tests userEntry and sets the boolean variable goodChoice to true if the userEntry is in the goodResponses list?
    1. for(x = 0; x < 4; ++x)
      if(userEntry = goodResponses) goodChoice == true;
    2. for(x = 0; x < 4; ++x)
      if(userEntry[x] = goodResponses[x]) goodChoice = true;
    3. for(x = 0; x < 4; ++x)
      if(userEntry = goodResponses[x]) goodChoice == true;
    4. for(x = 0; x < 4; ++x)
      if(userEntry == goodResponses[x]) goodChoice = true;
  14. Two arrays with the same number of elements and corresponding data are _____________.
    1. competitive
    2. illegal
    3. identical
    4. parallel
  15. Searching through an array for an exact match to some variable is a good idea when____________.
    1. no variable values ae invalid
    2. the variable values to be matched are sequential
    3. there ae relatively few possibilities for the value in the variable
    4. you need to match a variable based on a range of values
  16. If a test is graded so that a score of 90 or above is a A, 80 to 89 is a B, and so on, you can create a gradeLimit array ( int[] gradeLimit = {90, 80, 70, 60, 0}; ) and a grade array ( char[] grade = {'A', 'B', 'C', 'D', 'F'}; ). Which of the following satements assigns the correct grade to lettergrade variable based on the variable score?
    1. for(x = 0; x < 4; ++x)
      if(score >= gradeLimit[x]) letterGrade = grade[x];
    2. for(x = 4; x >= 0; --x)
      if(score >= gradeLimit[x]) letterGrade = grade[x];
    3. for(x = 0; x < 4; ++x)
      if(score >= grade[x]) letterGrade = grade[x];
    4. for(x = 4; x >=0; --x)
      if(score <= gradeLimit[x]) letterGrade = grade[x];
  17. When you pass an array element to a method, the method receives________________.
    1. a copy of the array
    2. the address of the array
    3. a copy of the value in the element
    4. the address of the element
  18. Arrays are passed by ___________.
    1. reference
    2. value
    3. referral
    4. copying
  19. When you pass an array to a method, the method receives _________.
    1. a copy of the array
    2. a copy of the first element in the array
    3. the address of the array
    4. nothing
  20. If you pass an array from a main() method to a method named changeIt(), and the method changes a value in the array, then _____________.
    1. you receive an error message
    2. the original array element in main() changes
    3. the original element in main() remains unchanged
    4. the original element in main() changes only if you return a value from the method


SECTION B

Strings

Declaring Strings

You learned in chapter 1 that a sequence of characters enclosed within double quotation marks is a literal string. You have used many literal strings, such as "First Java program", within println() statements. You can also create objects that hold a series of characters and have the type String.

You also use String in main() method headers.

The class String is defined in java.lang.String, which is automatically is imported into every program you write. You create a string object by using the keyword new and the String constructor method, just as you would creae an object of any other type. For example, String aGreeting = new String("Hello"); is a statement that defines and object named aGreeting, declares it to e of type String, and assigns an initial value of "Hello" to the String. Alternatively, you an declare a String containing "Hello" with String agreeting = "Hello";.

After declaring a String, you can display it in a print() or println() statement, just as you would for any other variable—for example System.out.println("The greeting is " + agreeting);.

Also, as with any other object, you can create an array of strings. Eor example, you can store three company department names as String[] deptName = {"accounting", "Human Resources", "Sales"};. You can access thes department name like any other array object. For example, to print them, you can use the following code:

for(int a = 0; a < deptName.length; ++a)
  System.out.println(deptName[a]);

Notice that deptName.length; refers to the length of the array depName (three elements), and not to the length of any of the string objects stored in the deptName array. Each String object has access to a length() method that returns the length of a String. For example, if depName[0] is "Accounting", then deptName[0].length() is 10.

Next, you will create two arrays to hold event types and manager names for Event Handlers Incorporated. Then, when a user enters and event type, the appropriate event type and manager name will display on the screen.

To add event types and manager names to the EventArray program;
  1. Open the EventArray.java file in your text editor, positon the cursor after the opening curly bracket of the main() method, and then press the Enter key to start a new line.
  2. Add the array of event types by entering the following:

    String[] eventType = {"Corporate", "Private", "Non-Profit");
  3. Press the Enter Key to start a new line, and then add the following array of manager names:

    String[] managerName = {"Dustin Britt", "Carmen Lindsey", "Robin Armenetti");
  4. Locate the for loop that determines if the user entered a valid code. Place the cursor after the statement codeIsValid = true; that appears within the for statement, and then press the Enter key to start a new line.

    At this point in the program, the variable i indicates the position of a correct event type in the eventCode array. The correct event type is in the same relative position in the eventType array as the correct manager's name is within the managerName array. In other words, managerName[I] "goes with" eventCode[i].
  5. Type the following statement that prints the event type and manager's name on the new line:

    System.out.println("The manager for " + eventType[i] + " event is " + managerName[i]);
  6. To simplify screen output, comment out the call to raiseRate() as well as the lines that print the raised rates. Type // at the begining of each of these lines.
  7. save, compile, and test the program. Your output should look like 5-14.

Comparing Strings

A string is and object, like an array. In many programming languages, you create a string by creating an array of characters. In the Java programming language, however, String is a class, and each created string is a class Object. Like and array object, or any other object, a string variable name is actually a reference; this is a string variable name actually refers to a location in memory rather than to a particular value.

The distinction is subtle, but when you declare a variable of a basic, primitive type, such as int X = 10;, the memory address where x is located holds the value of 10. If you later assign a new value to x—for example,x = 45;—then the value 45 replaces the 10 at the assigned memory address. When you declare a String as String aGreeting = "Hello";, aGreeting holds a memory address where the characters "Hello" are stored. If you subsequently assign a new value to aGreeting, such as aGreeting = "Bonjour"; then the address held by aGreeting is altered; now aGreeting = "Bonjour";, now a Greeting holds a new address where the characters "Bonjour" ae stored. "Bonjour" is an entirely new object created with its own location. The "Hello" string is actually still in memory; it's just that aGreeting isn't holding its address anymore. Eventually, a part of the Java system called the garbage collector will discard the "Hello" characters. Strings, therefore, are never actually changed; instead, new Strings are created and String variables hold the new addresses. Strings and other objects that can't be changes are known as immutable.

Because string variables hold memory addresses, you cannot make a simple comparison to determine whether two String objects ae equivalent. For example if you declare two Strings as String aGreeting = "Hello"; and String anotherGreeting = "Hello";, Java will evaluate a comparison such as if(aGreeting == anotherGreeting).. asfalse. When you compare aGreeting to anotherGreeting with the == operator, you are comparing their memory addresses, and not their values.

Fortunately, the string class provides you with a number of useful methods. The equals() method evaluates the contents of two String objects to determine if they are equivalent. The method returns true if the objects have identical contents. For example, 5-15 shows two String objects and several comparisons. Each of the comparisons in 5-15 are true; each comparison results in printing the line "Name's the same".

5-15String comparisons
String aName = "Roger";

String anotherName = "Roger";

if(aName.equals(anotherName));

   System.out.println("Name's the same"); if(anotherName.eguals(aName))

   System.out.println("Name's the same"); if(aName.equals("Roger");

   System.out.orintln("Name's the same");
The equals() method returns true only if two Strings are identical in content. thus a String holding "Roger " (with a space after the r) is not equivalent to a String holding "Roger" (with no space after the r).

Each String shown in 5-15—aName and anotherName—is an object of the type String, so each String has access to the equals() method. The aName object can call equals() with aName.equals(), or the anotherName object can call equals() with anotherName.equals(). The equals() method can take either a variable String object or a literal string as its argument.

The equalsIgnoreCase() method is very similar to the equals() method. As its name implies,it ignores case when determining if two Strings ae equivalent. Thus aName.equals("roGER") is false, but aName.equalsIgnoreCase("roGER") is true. This method is very useful when users type responses to prompts in your program. You can never predict wheb a user might use the Shift key or the Caps lock key during data entry. The equalsIgnoreCase() method allows you to test entered data without regard to capitalization.

The compareTo() method provides additional information. When you use compareTo() to compare two string objects, the method returns zero only if the two Strings hold the same value. If there is any difference between the Strings, a negative number is returned if the calling object is "less than" the argument, and a positive number is returned if the calling object is "more than" the arugment. Strings ae considered to be "less than" or "more than" each other based on their Unicode values; thus, "a" is less than "b" and "b" is less than "c".

For example, if aName holds "Roger", and the the method call aName.compareTo("Robert") returns a 5. the number is positive, indicating that "Roger" is more than "Robert". this does not mean that "Roger has more characters than "Robert"; it means that "Roger" is alphebetically "more" than "Robert". The comparison proceeds as follows:

Often, you don't care what the return value of compareTo() is specifically; you simply want to determine if it is positive or negative when, for example, attempting to place two strings in alphabetical order. For example, you can use a test such as if(aWord.compareTo(anotherWord) < 0)... to determine whether aWord is alphabetically less than another Word. If aWord is a String variable that holds the value "hamster", and anotherWord is a string variable that holds the value "iguanna", then the comparison if(aWord.compareTo(anotherWord)<0) yields true.

Next, you will compare two state names to each element in and array of Strings to determine whether each state name occurs within the array.

To compare a String to each element in and array:
  1. Open a new text file in your text editor, and then enter the following openin lines ofr a FindState class:

    public class Findstate
    {
       public static void main(String[] args)
       {
  2. Enter the following array of String objects that holds the state names where Event Handlers Incorporated has offices:

    String[] states = {"Alaska", "California", "Illinois", "Oregon", "Texas", "Wisconsin", "Wyoming"};
  3. For testing purposes, assign the following two state names to two string objects named firstSstate and secondState:

    String firstState = "Illinois";
       // This state will be found in the list
    String secondState = "Ohio"    // This state will not be found in the list
  4. Next, declare the following integer variable that you will use as a subscript, and a boolean varialbe that you will set to true when a state name is found in the array:

    int x; boolean found = false;
  5. Enter The following for loop that compares the first state to each state in the array. When a match is found, set the boolean found variable to true.

    for(x = 0; x < states.length; ++x)    if(firstState.equals(states[x]))       found = true;
  6. At the end of the loop, enter the following statements to print a statement indicating whether the firstState was found:

    if(found)
        System.out.println(firstState + " is in the list");
    else
        System.out.println(firstState + " is not in the list");
  7. Now enter the following statements to reset the variable found to false and then repeat the search process for the secondState variable:

    found = false;
    for(x = 0; x < states.length; ++x)
       if(secondState.equals(states[x]))
          found = true;
       if(found)       System.out.println(secondState + " is in the list');
       else
          System.out.println(secondState + " is not in the list");
  8. Enter the two closing curly brackets that end the main() method and the FindState class.
  9. Save the program as FindState.java in the Chapter.05 folder on your Student Disk. Compile the test program. The program's output appears in 5-16.

5-16: Output of the FindState program
wallen@wallen-desktop:~$ cd Desktop/Java/Chapter.05
wallen@wallen-desktop:~/Desktop/Java/Chapter.05$ javac
FindState.java
wallen@wallen-desktop:~/Desktop/Java/Chapter.05$ java FindState
Illinois is in the list
Ohio is not in the list
wallen@wallen-desktop:~/Desktop/Java/Chapter.05$

public class FindState
{
   public static void main(String[] args)
   {
   String[] states = {"Alaska", "California", "Illinois", "Oregon", "Texas", "Wisconsin", "Wyoming"};
   String firstState = "Illinois"; //This state will be found in the list
   String secondState = "Ohio"; // This state will not be found in the list
   int x;
   boolean found = false;
   for(x = 0; x < states.length; ++x)
         if(firstState.equals(states[x]))
         found = true;
   if(found)
      System.out.println(firstState + " is in the list");
   else
   System.out.println(firstState + " is not in the list");
   found = false;
   for(x = 0; x states.length; ++x)
      if(secondState.equals(states[x]))
         found = true;
      if(found)
         System.out.println(secondState + " is in the list");
      else
         System.out.println(secondState + " is not in the list");
   }
}

Using Other String Methods

A wide variety of additional String methods are available with the string class. The methods toUpperCase() and toLowerCase() convert any String to its uppercase or lower case equivalent. For example,if you declare a String as String aWord = "something"; then aWord = aWord.toUpperCase assigns 'SOMETHING" to aWord.

The method indexOf() determines whether a specific character occurs within a String. If it does, the method returns the position of the character. String positions, like array positions, begin with zero. The return value is -1 if the character does not exist in the String. For example, for String myName = "Stacy"; , the value of myName.indexOf('a') is 2, and the value of myName.indexOf('q') is -1.

The method charAt() requires and integer argument which indicates the position of the character the method returns. For example, if myName is a String holding "Stacy", then the value of myName.charAt(0) is 'S' and myName.charAt(1) is 't'.

The methods endsWith() and startsWith() each take a String argument and return true or flase if a String object does or does not end with or start with the specified argument. For example if String myName.startsWith("Sta") is true and myName.endsWith("z") is false.

The replace() method allows you to replace all occurrences of some character within a String. For example, if String yourName = "Annette";, then String goofyName = yourName.replace('n', 'X'); assigns "AXXette" to goofyName.

The toString() method converts any primitive type to a String. So, if you declare a String as theString and an integer as int someInt = 4;, then theString = toString(someInt); results in the String "4" being assigned to theString. The toString() method is not part of the String class; it is a method included in Java that you can use with any type of object. You actually have been using toString() throughout this book without knowing it. When you use print() and println(), their arguments are converted to Strings automatically if necessary.

You don't need import statements to use toString() because it is part of java.lang, which is imported automatically.
Because the toString() method takes arguments of any primitive type, including int, char, double, and so on, you know that it is an overloaded method.

You already know that you can join Strings with other Strings or values by using a plus sign (+); you have been using this approach in println() statements since Chapter 1. For example, you can print a firstName, a space, and a lastName with System.out.println(firstName + " " + lastName);. Joining Stsrings is called concatenation. Additionally, you can extract part of a string with the substring() method, and use it alone or concatenate it with another String. The substring method takes two arguments—a start positon and and end position—that are both based on the fact that a String's first position is the positon zero. For example the program segment 5-17 produces the output shown in 5-18

5-17 Program segment demonstrating String concatenation
String concatenation String[] dayOfWeek = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};

String sentence;

int x;

for(x = 0; x < dayOfWeek.length; ++x)

{

    sentence = "The abbreviation for " + dayOfWeek[x] + " is" + dayOfWeek[x].substring(0,3);

    System.out.println(sentence);

}

5-18Output of the String concatenation code segment
wallen@wallen-desktop:~$ cd Desktop/Java/Chapter.05
wallen@wallen-desktop:~/Desktop/Java/Chapter.05$ java StringConcatenation
The abbreviation for Monday is Mon
The abbreviation for Tuesday is Tue
The abbreviation for Wednesday is Wed
The abbreviation for Thursday is Thu
The abbreviation for Friday is Fri
wallen@wallen-desktop:~/Desktop/Java/Chapter.05$

To demonstrate the use of String methods, you will create a simple guessing game, similar to Hangman. The user will guess letters and attempt to guess the motto of Event Handlers Incorporated.

To create the guessing game:
  1. Open a new text file in our text editor. Enter the following first few lines of a SecretPhrase program. The program will contain the target phrase that the user will try to guess ("Plan With Us") as well as a display phrase taht is mostly asterisks (with a few hints).

    public class SecretPhrase
    {
       public static void main(String[] args) throws Exception
       {
          String targetPhrase = "Plan With Us";
          String dispalyPhrase = "P*** W*** U*";
  2. Add the following variables that will hold the user's guess and the positon of a guess that is found within the phrase:

    char guess; int position;
  3. Next add the following brief instruction:

    System.out.println("Play our game - guess ourmotto");
  4. Enter the statement to display the hint phrase:

    System.out.println(displayPhrase);
  5. Add the following loop that continues while asterisks remain in the displayPhrase. The user will enter a letter. You will use the indexOf() method to determine whether the guessed letters appears in the targetPhrase. If it does not, then ask the user to guess again. If the guessed letter appears in the phrase, you reconstruct the display phrase with the following:
    • The substring of characters in the display phrase that comes before the correct guess.
    • The correct guess.
    • The substring of characters in the display phrase that appears after the correct guess; in other words, the correct letter replaces sthe appropriate asterisk.


    while(displayPhrase.indexOf('*') != -1)
    {
      System.out.lprintln("enter a letter");
      guess = (char)System.in.read();
      System.in.read(); // Absorbs enter key
      positon = targetPhrase.indexOf(guess); // Determines position of guess
      if(position == -1) // If guess is not in target phrase
        System.out.println("Sorry - guess again");
      else // If guess is in target phrase
      {
        displayPhrase = displayPhrase.substring(0,positon) + guess + displayPharse.substring(position+1, displayPhrase.length());
        System.out.print(displayPhrase);
      }
    }
  6. The while loop will continue untill all the asterisks in the displayPhrase are replaced by replaced by correct letters. Therefore, after the closing curly bracket for the while loop, enter System.out.println("Congratulations!");;
  7. Type the closing curly brackets for the main() method and for the SecretPhrase class.
  8. Save the program as SecretPhrase.java in the Chapter.05 folder on your Student Disk, and then compile and run the program. Make sure you understand how all the String methods contribute to the success of this program.

. see SecretPhrase.java

wallen@wallen-desktop:~$ cd Desktop/Java/Chapter.05/
wallen@wallen-desktop:~/Desktop/Java/Chapter.05$ javac SecretPhrase.java
wallen@wallen-desktop:~/Desktop/Java/Chapter.05$ java SecretPhrase
Play our game - guess our motto
P*** W*** U*
Enter a letter
a
P*a* W*** U*
Enter a letter
l
Pla* W*** U*
Enter a letter
a
Pla* W*** U*
Enter a letter
n
Plan W*** U*
Enter a letter
o
Sorry - guess again
Enter a letter
i
Plan Wi** U*
Enter a letter
w
Sorry - guess again
Enter a letter
t
Plan Wit* U*
Enter a letter
s
Plan Wit* Us
Enter a letter
u
Sorry - guess again
Enter a letter
h
Plan With Us
Congratulations!
wallen@wallen-desktop:~/Desktop/Java/Chapter.05$

Converting Strings to Numbers

If a String contains all numbers, as in "649", you can convert it from a String to a number so you can use it for arithmetic, or use it like any other number. To convert a String to an integer, you use the Integer class, which is part of java.lang, and therefore automatically is imported into programs you write. A method of the Integer class is parseInt(), which takes a string argument and returns its integer value. For example, int anInt = Interger.parseInt("649"); stores the numeric value 649 in the variable anInt. You can then use the integer value just as you would anly other integer.

The word parse in English means "to resolve into component parts," as when you "parse a sentence." In Java, to parse a String means to break its separate characters into a numberic format.

It is only slightly more difficult to convert a String object to a double value. You must use the Double class, which, like the Integer class, also is imported into your programs automatically. Conversion to a double variable is a two-step process:

For example, to convet a String containing "147.82" to a double, you can use the following code:

String stringValue = new String("147.82"0;

Double tempValue = Double.valueOf(stringValue);

double doubleValue = doubleValue(tempValue);

The stringValue is passed to the Double.valueOf() method, which returns a Double object. The Double object, tempValue, is passed to the doubleValue() method, which returns a double variable.

The Double and Interger classes are examples of wrappers. A Wrapper is a class of object that is "wrapped around" a simpler thing. You use the Double (uppercase D) class to make it convenient to work wiht primitive double (lowercase d) variables.

When planning an event, Event Handlers Incorporated needs to know how many guests to expect. Next, you will prompt the user for the number of guests, red characters from the keyboard, store the characters in a St5ring, and then convert the String to an Integer.

To create a program that accepts integer input:
  1. Open a new text file in your text editor, and then enter the following first few lines of a NumInput class that will accept numberi input:

    public class NumInput
    {
      public static void main(String[] args) throws Exception
      {
  2. Declare the following variables to hold the input String, each character of input, and the rusulting integer:

        String inputString = new String();
        char newChar;
        int inputNumber:
  3. Prompt the user for the number of guests and readin the first character by entering the following lines:

        System.out.println("Enter the number of guests at your event");
        newChar = (char)System.in.read(0;
  4. Enter the following whileloop that continues while you continue to ewnter digits. Within the loop, you will take the current input String and concatenate each new character to it. Then read another new character before looping back to check ifthe next character is a digit.

        while(newChar >= '0' && newChar <= '9')
        {
          inputStsring = inputString + newChar;
          newChar = (char)System.in.read();
        }

  5. When the while loop ends, add the following read() statement to absorb the Enter key: System.in.read();
  6. Use the following Integer.parseInt() method to convert the input String to an integer. Then use the integer in a numberic decision.

    cd inputNumber = Integer.parseInt(inputStsring);
    if(inputNumber > 100) System.out.println("A surcharge will apply!");
  7. Enter the final two closing brackets tothe main program.
  8. Save the program as NumInput.java in the Chapter.05 folder on your Student disk, and then compile and test the program.

see NumInput.java

wallen@wallen-desktop:~$ cd Desktop/Java/Chapter.05
wallen@wallen-desktop:~/Desktop/Java/Chapter.05$ java NumInput
Enter the number of guests at your event
1000
A surcharge will apply!
wallen@wallen-desktop:~/Desktop/Java/Chapter.05$

SUMMARY