Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Chapter XII Java Static Arrays Chapter XII Topics 12.1 Introduction to Data Structures 12.2 One-Dimensional Array Definition 12.3 Accessing Array Elements by Index 12.4 List Class Case Study I 12.5 Accessing Array Elements with for..each 12.6 Array Processing with the Arrays Class 12.7 Command Prompt Keyboard Input 12.8 Static Imports 12.9 Summary Chapter XII Java Static Arrays 12.1 12.1 Introduction to Data Structures Early in the course you were introduced to simple data types, like int, float, char, double, and boolean. Each one of these data types can be used to create a variety of required variables. A simple data type variable is a location in memory that stores a single value that can be used by a computer program. Single values are practical for loop counter variables, maximum number of grades, the height of Pikes Peak and the number of medals won by the United States at the last Olympics. Programs that handle passenger airline reservations, student college transcripts, employee payroll records and hospital patient information, require massive data storage. Such major storage requirements cannot be handled efficiently by thousands of simple data type variables, each storing a single value. You will need more sophisticated data types. It can be argued that you have been storing multiple values inside objects since the very beginning, and that is very true. However, the data stored inside the classes and objects so far have been one or more simple data types. There are many situations where data needs to hold more than one value. Such a situation calls for using a data structure. So what is a data structure? Look at a building. Note that it is made up of smaller structures like rooms, halls, stairways, etc. A room is made up of walls, floors, ceilings, desks, chairs, etc. Another example can be found with animals. Animals are organisms made up of organ systems. Each organ system is made up of organs. Organs are made up of tissues, and tissues are made up of cells. We could continue and work down to the molecular and atomic level, but for this analogy, assume that the cell is the simplest, and lowest level. The whole point is that the structure, an organism in this case, is made up of other, smaller structures, until eventually you reach the smallest component. These two examples are used to motivate the definition of a data structure. In computer science it really is the same idea. The only difference in structures is the nature of the smallest building block used to create the structure. In an animal organism it is a cell. In a building it may be a brick or a plank and in a computer science data structure it is a simple data type. First Data Structure Definition A data structure is a data type whose components are smaller data structures and/or simple data types. 12.2 Exposure Java, 2006 Edition 10-27-06 You will note that it states First Data Structure Definition. This definition is not quite finished. We will revisit the data structure definition again and make some revisions. The complete, and more accurate, definition will only add unnecessary complexity right now. First we need to spend some time with a variety of data structure examples before it makes sense to become more precise. This approach is quite similar to teaching somebody to play a new card game. It just does not make sense to explain all the more intricate details of the game at the start of a new game. Frequently, the best approach is to deal the cards and explain as you go along. After several hands are dealt, it is easier to summarize a variety of rules. In other words, let us deal some hands first and then we talk some more. So what is the bottom line essence of this data structure, right now at this stage? Simple. You no longer have a data type that stores a single value. You can store more than one value in a data type that is a data structure. Put in other words, any data type that can store more than one value is a data structure. Data Structure Starting Point Any data type that can store more than one value is a data structure. All right, we have a starting point. Now we need to look and see what computer science has to offer for us in the data structures department. Exactly, what types of data structures exist and what can they do for us. You may have noticed that the title of this chapter talks about arrays, which is one kind of data structure. The importance of data structures is such that one chapter is devoted to each data structure. Since this is the very first chapter about any kind of data structure, it will help to give a brief overview of several different types of data structures. The Array Data Structure The array, or subscripted variable, is the first historical data structure. This data structure became popular in the first commercially-wide-used programming language, FORTRAN. FORTRAN (FORmula Translator) was designed for the scientific - number crunching - community. A data structure, like an array, was necessary for the storing of large quantities of numbers. Chapter XII Java Static Arrays 12.3 What does an array bring to mind? How about an array of flowers or an array of books, or an array of anything else? We think of an array as having multiple items - not a single item - and an array has the same type of items. We can have an array of integers, an array of real numbers, an array of characters, and an array of strings. An array can have any kind of element, as long as each element is the same data type. You will find the name vector used frequently for onedimensional arrays and matrix for two-dimensional arrays. First Array Definition An array is a data structure with one, or more, elements of the same type. A one-dimensional array is frequently also called a vector. A two-dimensional array is frequently also called a matrix. Once again you see this first definition expression. This is the same story as the data structure definition. All this business is tied together. More complete definitions will come later when each data structure is explained in more detail. The Record Data Structure The business community was not very happy with the FORTRAN language and particularly with the data structure limitation of having an array and nothing else. In the business world, data is not of the same type. This is lovely in science and math where numbers rule the discipline, but in business it is another story. Data storage in business requires storing names, addresses, birth dates, number of dependents, social security numbers, credit cards numbers, flight numbers, years worked, pay rates, credit balance available, etc. etc. etc. One solution was to create many different arrays. Each array specialized in one part of some business record. An array of names, an array of addresses, an array of pay rates and so on, which were called parallel arrays. This worked but it was tedious. A new programming language became popular, called COBOL (COmmon Business Oriented Language), which introduced the record data structure. What does the word record bring to mind? How about a student’s record, an employee’s record, a patient’s record, a passenger’s record. Each one of these 12.4 Exposure Java, 2006 Edition 10-27-06 records has the common thread of multiple information fields that can be of many different types. This type of data structure is precisely what the business world required. COBOL became a highly successful language (it helped that the Department of Defense adopted the language) and the record is now an integral part of programming. Initially, records only stored data of different types. Over time, records have evolved and now improved records store actions that process the data inside the same data structure. You have seen this improved record structure already in Java as the class, which is the primary component of Object Oriented Programming. First Record Definition A record is a data structure with one, or more, elements, called fields, of the same or different data types. The File Data Structure Programming languages have a convenient data structure that facilitates the transfer of data to and from external storage. The array and record may be lovely to store a complex set of data in the memory of a computer, but this data often needs to be used at some future date. The data needs to be stored in some permanent manner. The file data structure provides this ability. File Definition A file is an internal data structure - with an unspecified number of elements of the same type - assigned to an external file name. The file data structure allows transfer of data between internal and external storage. Chapter XII Java Static Arrays 12.5 Other Data Structures The three data structures - array, record (class now) and file - introduced in this section are built-in Java data types. These data types are ready to go and can be used with very little effort. Using built-in data structures is a good starting point in an introductory computer science course. There are many other types of data structures that the programmer can create for a wide variety of special purposes. The study and practice of these special user-created data structures is a major focus of the second year AP Computer Science course. One example of such a special data structure will be presented here, the stack. The Stack Data Structure One important data structure in computer science is the stack. This data structure will be explained, and used, in considerable detail in the future. Right now consider the following stack definition. Stack Definition A stack is a data structure with elements of the same type. Data elements of the stack data structure can only be accessed (stored or retrieved) at one end of the stack in a LIFO (Last In, First Out) manner. Let us go to a large home improvement store to create an analogy about this data structure business. You walk through one isle to get a variety of bolts and nuts of different sizes. All the hardware is neatly organized in separate containers that are clearly labeled. You might think that the isle containing all the screws, bolts, nuts and hooks is a large record of hardware data. There is one organized isle for many different types of hardware. You walk directly to a container that is marked with the size bolt that you need. After that you walk to another container that stores the correct sized nut that you need. This is random access. You can select to access any items in any random pattern. A little later you need to pick up a new lawnmower. All the new lawnmowers are stored in neat stacks, eight boxes high. The particular lawnmower that you need happens to be the third box from the bottom of one stack. It is not possible for you to access this lawnmower randomly. The stack only allows access at the top. Store employees carefully remove one box at a time with a forklift from the top of the stack, until your lawn mower can be accessed. This is not random access. 12.6 Exposure Java, 2006 Edition 10-27-06 Data access to the lawnmowers or a computer science stack is only possible at one end. Furthermore, the access is Last In, First Out (LIFO). Now why do you need to use a stack data structure in computer science? This is a topic for later discussion. Right now you need to learn about arrays. The forward peek to the stack was provided to make a relevant comparison of different data access. It was used strictly to help explain that the manner of data access is fundamental to a data structure's definition. The understanding and use of data structures is one of the most significant components of successful programming. You will be using many data structures, both Java provided data structures, and user-created data structures. The definition of a data structure, given at the beginning of this introduction -and this has been a long introduction -- will be repeated here. Look at this short sentence closely. The definition is strictly limited to the storing of information. Nothing is stated about how the information accessed. First Data Structure Definition A data structure is a data type whose components are smaller data structures and/or simple data types. This is precisely why this is called First Data Structure Definition. The definition was fine for the very first introduction of a data structure, but it is not complete. There is more to the story. Something has to be mentioned about the manner in which data is accessed. Let us make an analogy with a car here. A car is a complex piece of machinery that consists of many components. We can somewhat think of a car as a data structure with components like doors, lights, transmissions, radios, steering wheels, etc. It is not sufficient to define a car by specifying that the car has doors, lights, a transmission, a radio, a steering wheel, etc. The access of these components is a major part of the overall definition or understanding of the car. Do the doors only open with a key, or does it have remote access, or perhaps a combination code that must be entered to unlock the doors? Is the transmission automatic, or manual, and if it is manual, how many gears are there and what is Chapter XII Java Static Arrays 12.7 the pattern? Furthermore, is the transmission two-wheel drive or four-wheel drive? The steering wheel controls the direction of the car, but is it direct access or is it indirect access with power steering? These are all questions that must be answered before somebody purchases a car. The precise definition of a car cannot be summed up by its components. The manner in which the components are accessed or operate has to be part of a complete definition. The same is true with data structures. Yes, we need to know how data is stored and what type of data can be stored. One major difference between an array and a record is the fact that an array can only store data of the same type, while the record can store data of many different types. That is great, but it is not sufficient. How do we access the data and what can be done to the data is another question? Consider the following altered data structure definition. Improved Data Structure Definition A data structure is a data type whose components are smaller data structures and/or simple data types. The storing and retrieval of the data elements is performed by accessing methods that characterize the data structure. All of a sudden the clean and simple data structure definition has become rather nasty looking. Hopefully, it will not seem all that bad. The first sentence is old stuff. We have been there before talking about data storage. The second sentence explains that data has to be accessed and the manner in which data is accessed and processed defines the nature of the data structure. The remainder of this chapter will concentrate completely on arrays or subscripted variables. The long introduction was provided to get some basic feel about the nature of data structures. Do not be concerned if you know little about arrays. The purpose of this chapter is precisely to clarify the array data structure. Right now it is hoped that you have some feel for data structures in general 12.8 Exposure Java, 2006 Edition 10-27-06 12.2 One-Dimensional Array Definition What comes to mind when you think of an array? There is an array of flowers, and you may also have an array of Barbie dolls, or perhaps an array of kitchen pots and pans. In each case the array has a dual meaning. You are talking about more than one element. And you are also indicating that these elements are alike. They do not all need to be identical, but they are of an identical type. The array of flowers may include many different flowers, but they are all flowers. If we only consider data storage, the following array definition is quite adequate. The definition explains that an array is a data structure, and it explains that the multiple elements of the array are fixed in number and they are of the same type. This is the definition that was presented in the introduction, a few pages back. First Array Definition An array is a data structure with a fixed number of elements of the same type. Data structures are more than a means to store data. That was the main point made in switching from the first data structure definition to the improved data structure definition. The way in which the stored data is accessed is part of the data structure definition. This really is the essence of OOP encapsulation. Store both the data and the actions that access the data. This means that the first array definition is not complete. Some indication must be given about data access. Do not get too excited because Array data access is quite simple. Improved Array Definition An array is a data structure with a fixed number of elements of the same type. Every element of the array can be accessed directly. The improved array definition indicates that arrays can be accessed directly. How is this accomplished if there are many different values stored in the same data type? Arrays use some unique index or subscript to identify each element in the Chapter XII Java Static Arrays 12.9 data structure. The indexing approach is all around us. Streets are arrays of homes. It is not sufficient to state that you live on Main Street. You need something like 1750 Main Street. An airplane contains an array of seats, but flight 512 specifies the flight, not the location where you sit in the plane. A boarding pass will say something like Flight 512, Row 32, Seat D. A similar system applies to a football game’s reserved seat. Your ticket specifies the stadium and date along with the location of the seat. Another way to explain this array indexing business is to consider an array of desks in a classroom, more commonly known as a seating chart. Imagine that it is the first school day. Some teacher believes in assigned seats and also wants to be organized. Each student is given an assigned seat number. The teacher's seating chart, for Room J116 below, is one example. [16] Ingrid [17] Darlene [18] Gene [19] Sean [20] Stephanie [11] Holly [12] Blake [13] Michelle [14] Remy [15] Haley [06] Diana [07] Jessica [08] David [09] Anthony [10] Alec [01] Isolde [02] John [03] Greg [04] Maria [05] Heidi The seating chart demonstrates a very important array feature. Do not confuse the array index, with the contents at the array location, specified by the index. In other words, J116[08] is the desk for David. Room J116, seat number [08] is not equal to David. It is the location where David is supposed to sit. As you look at the examples in this chapter, and as you write your own programs with an array data structure, be aware of the difference between index and content. 12.10 Exposure Java, 2006 Edition 10-27-06 12.3 Accessing Array Elements by Index You have been around the variable declaration "block" long enough to know the routine. First you specify the data type and then you provide the identifier of the variable. This is wonderfully simple for data types like int, float, char, etc. With simple data types you get declarations that look like: int number; float gpa; char gender; While we are at it ... let us clear up some of this declaration and definition confusion. The declaration of a variable presents an identifier. We are proud to declare that a brand-new variable will be used and we declare its identifier or name to be number. But there is more to the story because number is an int variable and integers require four bytes of memory storage. This means that number requires four bytes of computer memory. Allocating four bytes of memory is the definition of number. This naming scheme has gone back and forth over the years and "old" computer science teachers like myself tend to chuckle because declarations used to be definitions and definitions used to be declarations. Why am I confusing you with this trivia? Simple, hopefully you are better prepared for the situation where you may find that explanations about definitions and declarations appear to be contradictory. You will observe that arrays use both declarations and definitions. First comes the declaration and then follows the definition. Figure 12.1 gives three Java array examples. The three examples each have two separate statements. The first statement declares an identifier to be some type of array. At first glance the declaration appears identical to the simple data type declaration that you have used frequently. The key difference is that a set of brackets follows the data type. These brackets signify that the data type is an array. So far this is purely a declaration and no memory has been established. The second statement should ring a bell. The new operator is used and hopefully you will jump to the immediate conclusion that a Java array must be a class. The second statement constructs (defines) a Java object and allocates memory. The size of the array is indicated in the second statement. Java will grab a solid block from memory so that each array element is adjacent to the next array element in memory. This is called a contiguous block of memory. Chapter XII Java Static Arrays 12.11 Figure 12.1 int list[ ]; list = new int[10]; // declares the array list identifier // allocates memory for 10 int variables char names[ ]; names = new char[25]; // declares the names array identifier // allocates memory for 25 char variables double grades[ ]; // declares the grades array identifier grades = new double[50]; // allocates memory for 50 double variables Now you are ready to learn how an array is used in a program. The first example will demonstrate how to display array values. Program Java1201.java, in figure 12.2, uses an array with 10 integers. There is little evidence that any values are assigned to the array elements. A for loop repeats with a loop control variable, k, from 0 to 9. The same k variable is used for the array index, like List[k]. As the value of k changes it displays each one of the 10 array elements. Figure 12.2 // Java1201.java // This program demonstrates how to declare an array of integers. // Note how each element of the array defaults to zero. // Java allows the display of uninitialized objects because object elements // get assigned values from the default constructor. public class Java1201 { public static void main(String args[]) { System.out.println("Java1201\n"); int list[]; // declares the array object identifier list = new int[10]; // allocates memory for 10 array elements for (int k = 0; k < 10; k++) System.out.println("list[" + k + "] = " + list[k]); System.out.println(); } } Java1201.java Output Java1201 List[0] List[1] List[2] List[3] List[4] List[5] List[6] List[7] List[8] List[9] 12.12 = = = = = = = = = = 0 0 0 0 0 0 0 0 0 0 Exposure Java, 2006 Edition 10-27-06 The output is quite boring. Every array element is 0. Actually, that is not half bad. It appears that Java integer arrays are constructed with 0 when there are no values assigned. Computer scientists frequently call arrays subscripted variables. The name subscripted variables comes from mathematics. In math you see expressions like X1 + X2 + X3 + ........... + Xn-1 + Xn . This indicates an array of numbers, all called X, and a subscript is used to indicate the first, second, third and so on value in the series. Java arrays, and really most programming languages, use a similar approach. It is awkward to write a program with an actual subscript so brackets are used to indicate the subscript or index of the array. You need to make another important observation from this first program example. The loop counter starts at 0 and stops at 9. This may seem odd to you. There are ten array elements. Why not count from 1 to 10. That may seem logical, and this is possible in some program languages. Languages like C and Java start array indexes at 0. There is a very logical reason for this approach, but for now you need to accept this as a Java fact. Array Index Note Java arrays indicate individual elements with an index inside two brackets, following the array identifier, like list[k]. The array index is always an integer and starts at 0. The first program example used the two-statements approach to declare and define an array in the program. It is possible to combine the two statements into one line in a more abridged format. Program Java1202.java, in figure 12.3, produces the exact same output as the previous program using the abridged array declaration and definition. Now I need to warn you here. I will go crazy if I have to continuously use the convoluted declaration, followed by definition language. So I will use the following convention. If declaration is used, it will mean that memory has not been allocated and the definition part will happen later. If definition is used than it means that the declaration has already been made or it is done in the same statement as the definition. My suspicion is that you probably do not care if computer scientists call this business a definition, a declaration or an Aardvark. Chapter XII Java Static Arrays 12.13 Figure 12.3 // Java1202.java // This program is almost identical to Java1201. The difference // is that the array declaration and array definition to allocate // memory is done in one program statement. public class Java1202 { public static void main(String args[]) { System.out.println("Java1202\n"); int list[] = new int[10]; // combined array declaration and definition for (int k = 0; k < 10; k++) System.out.println("list[" + k + "] = " + list[k]); System.out.println(); } } Java1202.java Output Java1202 List[0] List[1] List[2] List[3] List[4] List[5] List[6] List[7] List[8] List[9] = = = = = = = = = = 0 0 0 0 0 0 0 0 0 0 The two previous program examples both demonstrate that Java arrays with integer elements initialize each element of a new object to zero. Zeros are lovely, but can there be some other type of initialization? There is another approach, which is shown by program Java1203.java, in figure 12.4. In this example you will see that the statement new int[9] is replaced by {11,22,33,44,55,66,77,88,99}; The new operator is not necessary because the set of integer values implies that a new object needs to be constructed. Furthermore, it is also not necessary to indicate the quantity of the array object. This is provides by the count of the numbers between the braces. Finally, the provided integer set will be used to initialize each array element in the sequence that the numbers are placed. Defining an array object in this manner, with an initializer list, can be quite tedious for large arrays with hundreds or thousands of elements. On the other hand, a small array with a couple of dozen elements or less is handled very nicely with this approach. 12.14 Exposure Java, 2006 Edition 10-27-06 Figure 12.4 // Java1203.java // This program demonstrates how to initialize array elements. // The <new> operator is not necessary in this case. public class Java1203 { public static void main(String args[]) { System.out.println("Java1203\n"); int list[] = {11,22,33,44,55,66,77,88,99}; for (int k = 0; k < 9; k++) System.out.println("list[" + k + "] = " + list[k]); System.out.println(); } } Java1203.java Output Java1203 List[0] List[1] List[2] List[3] List[4] List[5] List[6] List[7] List[8] = = = = = = = = = 11 22 33 44 55 66 77 88 99 To declare an array of some other simple type follows the same procedure. Program Java1204.java, in figure 12.5, shows how to declare character arrays both initialized without some specified values and initialized with a set of specified characters. Figure 12.5 // Java1204.java // This program demonstrates how to declare an array of characters. // Are the array elements initialized to any kind of value? public class Java1204 { public static void main(String args[]) { System.out.println("Java1204\n"); char list1[] = new char[5]; for (int k = 0; k < 5; k++) System.out.println("list1[" + k + "] = " + list1[k]); System.out.println(); char list2[] = {'c','h','a','r'}; for (int k = 0; k < 4; k++) System.out.println("list2[" + k + "] = " + list2[k]); System.out.println(); } } Chapter XII Java Static Arrays 12.15 Figure 12.5 Continued Java1204.java Output Java1204 List1[0] List1[1] List1[2] List1[3] List1[4] = = = = = List2[0] List2[1] List2[2] List2[3] = = = = c h a r The output of list1 is quite meager. There appear to be no values stored in the character array at all after list1 is constructed. The previous integer arrays initialized to 0. What is the character equivalent of the number 0? Is it an empty character, a blank space or nothing at all? At least constructing a character array with a provided value set caused no alarm. All the provided characters are stored and displayed in the expected order. There still is the unanswered question of just what is initialized in a character array when no values are provided? Program Java1205.java, in figure 12.6, may provide an answer. In that program print is used in place of println to display each one of the character array values. Furthermore, a Start and End text display is shown before and after the characters are displayed. The list1 object has ten values. If the values are completely empty nothing will be displayed. On the other end if the values are invisible spaces then the evidence will show that Start and End are separated by ten spaces. Figure 12.6 // Java1205.java // The purpose of this program is to investigate the type of character that is // used to initialize a character array. Is it no-character-at-all or a blank space? public class Java1205 { public static void main(String args[]) { System.out.println("Java1205\n"); char List1[] = new char[10]; System.out.print("Start"); for (int K = 0; K < 10; K++) System.out.print(List1[K]); System.out.println("End"); System.out.println(); } } 12.16 Exposure Java, 2006 Edition 10-27-06 Figure 12.6 Continued Java1205.java Output Java1205 Start End It turns out that our second assumption is correct. Ten spaces are inserted between the Start and End output display. This means that character arrays are initialized with blank characters or space characters when an object is constructed without provided values. Perhaps this does not display at the top of your things I always wanted to know list, but it makes for good conversation. Imagine the rise of your popularity when you ask with confidence: Do you know how a character array object is initialized in Java, when no values are provided? Will a String array behave pretty much like a character array by assigning a space character to array elements without a provided value? That seems to be a logical assumption, but you must realize that characters and strings are not necessarily in the same behavior category. Program Java1206.java, in figure 12.7, shows two String arrays, and as before, with provided values and without any values. Once again the excitement mounts to see what will happen. Your wait is very short, and you will note that String arrays behave differently from char arrays. An unspecified String array is initialized to the value null. This is a special keyword, which indicates that there is no practical value stored yet. It is the String equivalent of the integer value of 0. The true meaning of null will be explained in a later chapter. Figure 12.7 // Java1206.java // This program demonstrates how String objects are initialized, // both without and with specified array values. public class Java1206 { public static void main(String args[]) { System.out.println("Java1206\n"); String list1[] = new String[5]; for (int k = 0; k < 5; k++) System.out.println("list[" + k + "] = " + list1[k]); System.out.println(); String list2[] = {"AAA","BBB","CCC","DDD","EEE"}; for (int k = 0; k < 5; k++) System.out.println("list2[" + k + "] = " + list2[k]); System.out.println(); } } Chapter XII Java Static Arrays 12.17 Figure 12.7 Continued Java1206.java Output Java1206 List[0] List[1] List[2] List[3] List[4] List2[0] List2[1] List2[2] List2[3] List2[4] = = = = = null null null null null = = = = = AAA BBB CCC DDD EEE Hard coding array elements during an array definition is tedious. Entering array elements during program execution also becomes quite annoying when there are many numbers to be added. Frequently, in the process of learning computer science it is important to process a large quantity of data, and such data in many cases does not need to be any specific values. In other words, random data is just fine. The only issue left is the nature of the random data. Are integers, real numbers, characters or strings required? In this brief section you will learn how to assign a variety of data types randomly to an array. In an earlier Chapter you learned how to generate random integers with the Random class and the nextInt method. You also learned how to construct Random objects with a seed passed to the constructor. The seed insures that every program execution produces an identical set of numbers. If you are rusty with controlling random integers, go back to Chapter VI and see how the Random class and the nextInt method can be used to generate any desired range of random integers. Program Java1207.java, in figure 12.8, demonstrates how to generate random numbers in a specified range, which is [100..999] in this case, and assign these numbers to a sequence of integer array elements. 12.18 Exposure Java, 2006 Edition 10-27-06 Figure 12.8 Continued // Java1207.java // This program fills an integer array with a random set of numbers. import java.util.Random; public class Java1207 { public static void main(String args[]) { System.out.println("Java1207\n"); int list[] = new int[20]; Random random = new Random(12345); for (int k = 0; k < 20; k++) list[k] = random.nextInt(900) + 100; for (int k = 0; k < 20; k++) System.out.println("list[" + k + "] = " + list[k]); System.out.println(); } } Java1207.java Output Java1207 List[0] = 851 List[1] = 680 List[2] = 241 List[3] = 928 List[4] = 458 List[5] = 284 List[6] = 575 List[7] = 802 List[8] = 701 List[9] = 889 List[10] = 717 List[11] = 142 List[12] = 890 List[12] = 206 List[14] = 312 List[15] = 584 List[16] = 687 List[17] = 803 List[18] = 432 List[19] = 775 Program Java1208.java, in figure 12.9, demonstrates the length keyword, which has nothing to do with randomness. Length is too small a topic to devote an entire section to it and length will be used frequently in future program examples. Arrays provide a convenient way to know how large an array is. It is possible to keep track of the size of an array with a special variable, but you can use length at any time to determine the size of the array. Chapter XII Java Static Arrays 12.19 The length keyword is somewhat of a strange creature. You may be tempted to use syntax like List.length(), because the dot notation does give the impression that length is a method of the List object, but in reality length is a field. Figure 12.9 // Java1208.java // This program introduces the length field to determine the // number of elements in the array. Remove the comments from line 16 // to observe what happens when the length field is altered. public class Java1208 { public static void main(String args[]) { System.out.println("Java1208\n"); String names[] = {"Joe","Tom","Sue","Meg"}; int n = names.length; // data field access; not a method call System.out.println("There are " + n + " array elements."); for(int k = 0; k < n; k++) System.out.println("names[" + k + "] = " + names[k]); // names.length = 10; System.out.println(); } } Java1208.java Output Java1208 There are 4 array elements. Names[0] = Joe Names[1] = Tom Names[2] = Sue Names[3] = Meg Random strings are an interesting problem. Java does not have a random string method floating around. There are an incredible number of possible strings and a random string method would be very cumbersome, and actually totally unnecessary. An array of strings or an array of any conceivable data type will still always use an integer value for the index. Consider the seating chart, shown earlier, and imagine a teacher randomly generating numbers to call on students. As numbers pop up, the teacher treats each number as a reference or index to a desk, looks at the seating chart and then calls on the student by name. It is also possible that the teacher keep the responsibility of knowing the index with the student. A rude teacher might call on a student strictly by using the desk number. We have example of this type of dehumanizing in prisons and other large institutions. 12.20 Exposure Java, 2006 Edition 10-27-06 At any rate you should be convinced that we can map a numerical value, which will be used to identify an array index, with the contents at that indexed location. The contents can be anything, but the index will always be an integer in a range starting at zero and going up to one less than the number of elements in the array. Program Java1209.java, in figure 12.10, constructs an array object with eleven strings. A loop is used to display a random string eleven times. Now do not expect to see each and every string once only. The nature of randomness is that some strings will be displayed twice while other strings may not be displayed at all. Your display should match the one in the book, as long as you use the same 12345 seed to construct the random object. Figure 12.10 // Java1209.java // This program demonstrates how to create an array of random strings. import java.util.Random; public class Java1209 { public static void main(String args[]) { System.out.println("Java1209\n"); Random random = new Random(12345); int rndInt; String names[] = {"AA","BB","CC","DD","EE","FF","GG","HH","II","JJ"}; for(int k = 1; k < 15; k++) { rndInt = random.nextInt(names.length); System.out.println("names[" + rndInt + "] = " + names[rndInt]); } System.out.println(); } } Java1209.java Output Java1209 Names[9] Names[7] Names[9] Names[8] Names[8] Names[1] Names[6] Names[0] Names[1] Names[0] Names[7] Names[8] Names[0] Names[3] = = = = = = = = = = = = = = JJ HH JJ II II BB GG AA BB AA HH II AA DD Chapter XII Java Static Arrays 12.21 12.4 List Class Case Study I In the case study department this will surely rank as a mini case study, but it is a case study nevertheless. The purpose of a case study is to help a student comprehend a fairly complex program or concept and to explain the stages along the way. Presenting a final product all at once can be quite overwhelming and produces confusion along with a healthy dose of anxiety. This section is also called Case Study I, because the List Class will be continued at a later chapter when additional tools are available to get really serious with this class. Every array example in this chapter has been presented as part of the main method. This approach has introduced array concepts, but it does not demonstrate how programs are designed in an Object Oriented Programming world. Think about a list in general. What does a list store and what does it do? Lists store information. There can be a list of account numbers, a list of people coming to a party, a list of students graduating, a list of girls you might ask to prom, and a list of girls who already have prom dates, to mention just a few examples. What can you do with objects of a List class? You can enter specific elements in a list. You can assign random values to a list. You can display the elements of a list. You can add elements to a list. You can delete elements from a list. You can sort the elements in a list. You can search for a specific element in a list. This is a fairly healthy list (pun intended) of actions that can be done with the data of a list. Only a few of these actions will be shown in this chapter. In a later chapter you will learn algorithms that insert, delete, sort and search and at that time you will return to the List case study to complete all the methods that were just mentioned, but are not implemented in this chapter. So let us get started. Two pieces of information will be stored in our List class: an array of integers and the size of the array. Yes, arrays can determine their own length, but I like to have my own private variable to store the size of the array. The first stage, Java1210.java, shown in figure 12.11, provides a constructor method and a second method to display the data. 12.22 Exposure Java, 2006 Edition 10-27-06 Figure 12.11 // Java1210.java // This program is the first stage in the List class. At this stage the // List class only initializes an array and displays its default values. public class Java1210 { public static void main(String args[]) { System.out.println("Java1210\n"); List1 listA = new List1(10); listA.display(); List1 listB = new List1(15); listB.display(); System.out.println(); } } class List1 { private int intArray[]; private int size; // stores array elements // number of elements in the array public List1(int s) { size = s; intArray = new int[size]; } public void display() { for (int k = 0; k < size; k++) System.out.print(intArray[k] + " "); System.out.println(); } } Java1210.java Output Java1210 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 Two List objects are constructed, one with ten integers and a second one with fifteen integers. The output display is not surprising with two sets of zero-valued arrays. No values are assigned and our lists only store zeroes. Now how is a List object created? Figure 12.12 shows the instantiation of a List object as well as the constructor that will create the new object. We are working with a List class, but the classes are intentionally numbered to help keep track of each stage in the List class. It will also help to prevent bytecode file problems. This way it is possible to compile an entire set of Java files without running into duplicate class names. Chapter XII Java Static Arrays 12.23 Figure 12.12 public List1(int s) { size = s; intArray = new int[size]; } ………………………………… List1 listA = new List1(10); ………………………………… We now see a good example of declaration and definition. The declaration of the List1 class cannot allocate memory. That is only possible when an object of the List1 class is constructed. This means that the intArray = new int[size]; statement needs to be placed inside a constructor. You now see another practical use for a constructor. Without a constructor you would not be able to have an object as a member of another object. This is called composition. The first List stage only works with default-valued array. In the second stage, shown by program Java1211.java in figure 12.13, a method is added to assign random integers in the [1000..9999] range to a List2 object. Note that the data of the List2 class is private and the accessing methods are public. That way any client of the List2 class has access to the stored data, but only indirectly with special accessing methods. Figure 12.13 // Java1211.java // This is the second stage of the List class. A method for assigning // random integers has been added. import java.util.Random; public class Java1211 { public static void main(String args[]) { System.out.println("Java1211\n"); List2 listA = new List2(10); listA.Display(); listA.Assign(); listA.Display(); System.out.println(); } } class List2 12.24 Exposure Java, 2006 Edition 10-27-06 { private int intArray[]; private int size; // stores array elements // number of elements in the array public List2(int s) { System.out.println("\nCONSTRUCTING NEW LIST OBJECT WITH DEFAULT VALUES"); size = s; intArray = new int[size]; } public void Assign() { System.out.println("\nASSIGNING RANDOM VALUES TO LIST OBJECT"); Random random = new Random(12345); for (int k = 0; k < size; k++) intArray[k] = random.nextInt(9000) + 1000; } public void Display() { System.out.println("\nDISPLAYING ARRAY ELEMENTS"); for (int k = 0; k < size; k++) System.out.print(intArray[k] + " "); System.out.println(); } } Java1211.java Output Java1211 CONSTRUCTING NEW LIST OBJECT WITH DEFAULT VALUES DISPLAYING ARRAY ELEMENTS 0 0 0 0 0 0 0 0 0 0 ASSIGNING RANDOM VALUES TO LIST OBJECT DISPLAYING ARRAY ELEMENTS 6251 6080 9241 1828 4055 2084 2375 9802 2501 5389 It is possible to have multiple constructors for the same class. This is called overloading. The Java compiler does not get confused when multiple methods are declared using the same identifier. This works as long as each method with the same name has a different signature. The signature, which presents a different set of parameters, distinguishes the appropriate method. Figure 12.14 shows both List3 constructors. Note how both constructors have the same List3 identifier, but the number of parameters is different. Chapter XII Java Static Arrays 12.25 Figure 12.14 public List3(int s) { System.out.println("LIST OBJECT WITH DEFAULT VALUES"); size = s; intArray = new int[size]; } public List3(int s, int n) { System.out.println("LIST OBJECT WITH SPECIFIED VALUES"); size = s; intArray = new int[size]; for (int k = 0; k < size; k++) intArray[k] = n; } The first List3 (default values) constructor allows the instantiation of a new List3 object with a specified number of elements. Each one of the elements will be assigned default values of 0. The second List3 (specified values) constructor also specifies the number of array elements and additionally adds a parameter for the value to be assigned to each array element. Program Java1212.java, in figure 12.15, creates two List3 objects using the two different constructors. Additionally, the assign method overrides the initial values created during construction and assigns a set of random values. 12.26 Exposure Java, 2006 Edition 10-27-06 Figure 12.15 // Java1212.java // A second "overloaded" constructor has been added to the third stage of the // List class. The second constructor specifies the initial array values. import java.util.Random; public class Java1212 { public static void main(String args[]) { System.out.println("Java1212\n"); List3 listA = new List3(10); listA.Display(); List3 listB = new List3(10,999); listB.Display(); listB.Assign(); listB.Display(); System.out.println(); } } class List3 { private int intArray[]; // stores array elements private int size; // number of elements in the array public List3(int s) { System.out.println("\nCONSTRUCTING NEW LIST OBJECT WITH DEFAULT VALUES"); size = s; intArray = new int[size]; } public List3(int s, int n) { System.out.println("\nCONSTRUCTING NEW LIST OBJECT WITH SPECIFIED VALUES"); size = s; intArray = new int[size]; for (int k = 0; k < size; k++) intArray[k] = n; } public void Assign() { System.out.println("\nASSIGNING RANDOM VALUES TO LIST OBJECT"); Random random = new Random(12345); for (int k = 0; k < size; k++) intArray[k] = random.nextInt(9000) + 1000; } public void Display() { System.out.println("\nDISPLAYING ARRAY ELEMENTS"); for (int k = 0; k < size; k++) System.out.print(intArray[k] + " "); System.out.println(); } } Chapter XII Java Static Arrays 12.27 Figure 12.15 Continued Java1212.java Output Java1212 CONSTRUCTING NEW LIST OBJECT WITH DEFAULT VALUES DISPLAYING ARRAY ELEMENTS 0 0 0 0 0 0 0 0 0 0 CONSTRUCTING NEW LIST OBJECT WITH SPECIFIED VALUES DISPLAYING ARRAY ELEMENTS 999 999 999 999 999 999 999 999 999 999 ASSIGNING RANDOM VALUES TO LIST OBJECT DISPLAYING ARRAY ELEMENTS 6251 6080 9241 1828 4055 2084 2375 9802 2501 5389 This has not been much of a case study. Only three brief examples were shown of the List class. This case study will grow and there are future stages where methods will be added that insert, delete, sort and search the arrays. This initial stage is good for starters. Teachers, and students familiar with other program languages, might wonder why the traditional sort and search algorithms are not placed in this chapter. The majority of computer science textbooks, including my own Exposure C++, introduce the first set of sort and search algorithms in the array chapter. I have found over the years that the array chapter, combined with sorting and searching, makes for a pretty overwhelming chapter. 12.5 Accessing Array Elements with for..each The for loop was introduced back in Chapter V, at least the type-of for loop that uses a loop control variable. Java version 5.0 introduced an enhanced for loop. This new-and-improved loop structure can manage access to array elements without using an index. A loop counter is not necessary, because the loop iterates until every element of the array has been accessed. 12.28 Exposure Java, 2006 Edition 10-27-06 Program Java1213.java, in figure 12.16, compares the old for-loop with the new for loop. You will note that the syntax of the enhanced for loop has simpler syntax. Inside the parentheses you need to use the name of the data structure, like list and a variable that is the same type as each array element. Figure 12.16 // Java1213.java // This program introduces the Java5.0 enhanced <for> loop // with an <int> array. public class Java1213 { public static void main(String args[]) { System.out.println("Java1213\n"); int list[] = {11,22,33,44,55,66,77,88,99}; for (int k = 0; k < 9; k++) System.out.print(list[k] + " "); System.out.println("\n\n"); // Old <for> loop syntax for (int item: list) System.out.print(item + " "); System.out.println("\n\n"); // New <for> loop syntax } } Java1213.java Output Java1213 11 22 33 44 55 66 77 88 99 11 22 33 44 55 66 77 88 99 Program Java1214.java, in figure 12.17, uses the new for loop to display the elements of a String array. Note the use of the identifiers. The array data structure is called names, implying more than one value. The identifier of each array element is called name, implying a single value. It is a small detail, but it is part of good program design to use practical, self-documenting identifiers. With small programs, program readability is not such a big deal. As programs grow and start to become thousands of lines of program code, you will truly appreciate identifiers that clearly indicate the nature of the stored value. Chapter XII Java Static Arrays 12.29 Figure 12.17 // Java1214.java // This program uses the Java5.0 <for> loop with a <String> array. public class Java1214 { public static void main(String args[]) { System.out.println("Java1214\n"); String names[] = {"Tom","Sue","Joe","Jan","Bob","Lee","Ann","Meg"}; for (int k = 0; k < 8; k++) System.out.print(names[k] + " "); System.out.println("\n\n"); // Old <for> loop syntax for (String name: names) System.out.print(name + " "); System.out.println("\n\n"); // New <for> loop syntax } } Java1214.java Output Java1214 Tom Sue Joe Jan Bob Lee Ann Meg Tom Sue Joe Jan Bob Lee Ann Meg The new for loop can be used with many different data structures. Essentially, an object is required. Program Java1215.java, in figure 12.18, demonstrates an array of String values. This creates an object of objects. The names array is an object and each array element, which is a String value, is also an object. This means that the new for loop can use the general data type Object. This generalization business will not seem quite so significant right now, but in the near future you will find that there are good reasons to make generalizations about your data types. Many text books, including this one, use a technique whereby the foundation for a future topic or concept is provided early. When the new topic is truly introduced in a serious manner, students already have some elementary insight. This approach helps to eliminate new-topic-anxiety. At least that is the aim. If anxiety is not relieved, well I am sorry. I did try. 12.30 Exposure Java, 2006 Edition 10-27-06 Figure 12.18 // Java1215.java // This program demonstrates a very generalized <for. each> loop usage // with the <Object> class. public class Java1215 { public static void main(String args[]) { System.out.println("Java1215\n"); String names[] = {"Tom","Sue","Joe","Jan","Bob","Lee","Ann","Meg"}; for (int k = 0; k < 8; k++) System.out.print(names[k] + " "); System.out.println("\n\n"); for (Object obj: names) System.out.print(obj + " "); System.out.println("\n\n"); } } Java1215.java Output Java1215 Tom Sue Joe Jan Bob Lee Ann Meg Tom Sue Joe Jan Bob Lee Ann Meg Enhanced for Loop The enhanced for loop is called the "for .. each" loop. This loop structure is available Java 5.0. The new loop structure does not replace the older for loop, because it is not possible to access specific array elements. int numbers[ ] = {1,2,3,4,5,6,7,8,9}; for (int number: numbers) System.out.print(number + " "); Chapter XII Java Static Arrays 12.31 12.6 Array Processing with the Arrays Class Program design includes two related concepts. First, there is the business of abstraction, which is the process of utilizing program features without any concern about the implementing of such features. Second, there is the process of implementing features based on certain specifications. Using existing methods without concern about the details of the methods is certainly easier than creating your very own code to write the methods you need. Basically, this means to use what is already available. Do not reinvent the wheel. At the same time, it is not possible to have tools available for every possible program need. You will need to design and implement your own classes and methods. You will need to know both how to use existing tools and create your own tools. Data structures require processing. Array processing includes element display, assigning values, sorting elements and searching elements. Java has very conveniently provided us with an Arrays class, which can perform all these array processing needs. AP Computer Science Examination Alert The Arrays class is not part of the AP Java Subset and will not be tested. Students are expected to know how to use and implement array algorithms, such as traversing, element access, sorting and searching. In this chapter these array algorithms are used with the provided Arrays class methods. In a future Algorithm chapter you will learn how to implement these methods yourself. 12.32 Exposure Java, 2006 Edition 10-27-06 Displaying Array Elements with toString All the previous program examples required a loop structure to display array elements. You learned how to use both an old for loop and a new for loop to access, and display, array elements. However, old or new, a loop structure was required to visit array elements. In program Java1216.java, in figure 12.19, you see that the elements of four different array objects are displayed with the help of the toString method of the Arrays class. Method toString, like all Arrays methods, is static, which means that you need to use the Arrays identifier. Figure 12.19 // Java1216.java // This program introduces the static <Arrays> class. // In this program the <toString> method is used to display the array elements. import java.util.Arrays; // necessary to use the <Arrays> class public class Java1216 { public static void main (String args[]) { System.out.println("Java1216\n"); int list1[] = {11,22,33,44,55,66,77,88,99}; double list2[] = {1.1,2.2,3.3,4.4,5.5,6.6,7.7,8.8,9.9}; char list3[] = {'A','B','C','D','E','F','G','H','I'}; String list4[] = {"AA","BB","CC","DD","EE","FF","GG","HH","II"}; System.out.println(Arrays.toString(list1)); System.out.println(Arrays.toString(list2)); System.out.println(Arrays.toString(list3)); System.out.println(Arrays.toString(list4)); System.out.println("\n\n"); } } Java1216.java Output Java1216 [11, 22, 33, 44, 55, 66, 77, 88, 99] [1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9] [A, B, C, D, E, F, G, H, I] [AA, BB, CC, DD, EE, FF, GG, HH, II] Chapter XII Java Static Arrays 12.33 Class Arrays, Method toString Method toString displays the elements of an array object separated by commas and bounded by square brackets. int list[] = {11,22,33,44,55,66,77,88,99}; System.out.println(Arrays.toString(list)); Assigning Array Element Values with fill It is possible to assign values to an array object with an initializer list. This is convenient and practical if the list is fairly small. The biggest advantage is that the initializer list can assign different values to every array element location. Program Java1217.java, in figure 12.20, shows that it is also possible to assign the same value to each array element using the fill method. The size of the array does not matter, but you can only assign the same values to every array element. Figure 12.20 // Java1217.java // This program demonstrates the <fill> method of the <Arrays> class. // The <fill> method assigns the same value to every array element. import java.util.Arrays; // necessary to use the <Arrays> class public class Java1217 { public static void main (String args[]) { System.out.println("Java1217\n"); int list1[] = new int[10]; double list2[] = new double[10]; char list3[] = new char[10]; String list4[] = new String[10]; Arrays.fill(list1,123); Arrays.fill(list2,1.23); Arrays.fill(list3,'Q'); Arrays.fill(list4,"USA"); System.out.println(Arrays.toString(list1)); System.out.println(Arrays.toString(list2)); System.out.println(Arrays.toString(list3)); System.out.println(Arrays.toString(list4)); System.out.println("\n\n"); } } 12.34 Exposure Java, 2006 Edition 10-27-06 Figure 12.20 Continued Java1217.java Output Java1217 [123, 123, 123, 123, 123, 123, 123, 123, 123, 123] [1.23, 1.23, 1.23, 1.23, 1.23, 1.23, 1.23, 1.23, 1.23, 1.23] [Q, Q, Q, Q, Q, Q, Q, Q, Q, Q] [USA, USA, USA, USA, USA, USA, USA, USA, USA, USA] Class Arrays, Method fill Method fill assigns the same value to every array element. int list1[] = new int[10]; double list2[] = new double[10]; char list3[] = new char[10]; String list4[] = new String[10]; Arrays.fill(list1,123); Arrays.fill(list2,1.23); Arrays.fill(list3,'Q'); Arrays.fill(list4,"USA"); Sorting Array Elements with sort Sorting is an extremely important array process. Why exactly is sorting so important? Do we like to see elements appear in sorted sequence? The answer is much simpler. Sorting is important, because there is a need to search data. Every time that a credit card is approved for a purchase, the credit card holder's information must be found before approval is granted. Does the card exist? Is there sufficient credit left on the account for the purchase? These questions can only be answered after performing a search, and searching is far more efficient when items are sorted. Just imagine finding somebody's phone number in a telephone book where the names are not sorted. Chapter XII Java Static Arrays 12.35 Program Java1218.java, in figure 12.21, demonstrates the sort method. Four arrays are sorted in ascending order. For characters and strings this means in alphabetical order. Do keep in mind that sorting with characters and strings is based on the numerical values of the characters. This can have some interesting results. Lower-case 'a' has a larger numerical code than upper-case 'Z', which means that in a mixed upper-case/lower-case sorting environment, you will find that the Z will be placed before the a. Notice that the program output for list5 does not appear correct. Correct sorting of strings requires that the strings are all lower-case or all upper-case. Figure 12.21 // Java1218.java // This program demonstrates the <sort> method of the <Arrays> class. // Method <sort> arranges array elements in ascending order. import java.util.Arrays; // necessary to use the <Arrays> class public class Java1218 { public static void main (String args[]) { System.out.println("Java1218\n"); int list1[] = {11,99,22,88,33,77,44,66,55}; double list2[] = {1.1,2.2,3.3,4.4,5.5,6.6,7.7,8.8,9.9}; char list3[] = {'A','I','B','H','C','G','D','F','E'}; String list4[] = {"AA","II","BB","HH","CC","GG","DD","FF","EE"}; String list5[] = {"aardvark","bobcat","cougar","dog","ELEFANT","FOX","GORILLA","HARE"}; Arrays.sort(list1); Arrays.sort(list2); Arrays.sort(list3); Arrays.sort(list4); Arrays.sort(list5); System.out.println(Arrays.toString(list1)); System.out.println(Arrays.toString(list2)); System.out.println(Arrays.toString(list3)); System.out.println(Arrays.toString(list4)); System.out.println(Arrays.toString(list5)); System.out.println("\n\n"); } } Java1218.java Output Java1218 [11, 22, 33, 44, 55, 66, 77, 88, 99] [1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9] [A, B, C, D, E, F, G, H, I] [AA, BB, CC, DD, EE, FF, GG, HH, II] [ELEFANT, FOX, GORILLA, HARE, aardvark, bobcat, cougar, dog] 12.36 Exposure Java, 2006 Edition 10-27-06 Class Arrays, Method sort Method sort arranges the array elements in ascending order. String and character array elements are sorted in ascending order of the numerical code values. Incorrect processing may occur if string values are mixed upper-case and lower-case. int list1[] = {11,99,22,88,33,77,44,66,55}; double list2[] = {1.1,2.2,3.3,4.4,5.5,6.6,7.7,8.8,9.9}; char list3[] = {'A','I','B','H','C','G','D','F','E'}; Arrays.sort(list1); Arrays.sort(list2); Arrays.sort(list3); Searching Array Elements with binarySearch The sort method does not give a clue how array elements are sorted. The method is simply called sort. On the other hand, the Arrays search method is called binarySearch, which is one specific searching process. You will fully appreciate the mechanics of the binary search in the later algorithm chapter. Right now a brief explanation will help to clarify the name. Think of the manner in which you search for a name in a telephone book. You know that the names are in alphabetical order. Few people start at the first page and steadily work forward. No, you roughly split the book open at some estimate location and conclude that you need to move forward or backward. Each time an ever smaller section is split again until the correct page is found. Program Java1219.java, in figure 12.22, demonstrates the binarySearch method. It returns the index of the array element if the element value exists. A negative index value is returned if the element does not exist. Remember that the first element in an array object start with index zero. Chapter XII Java Static Arrays 12.37 Figure 12.22 // Java1219.java // This program demonstrates the <binarySearch> method of the <Arrays> class. // Method <binarySearch> returns the index of a search element if it exists, // and returns a negative index value otherwise. import java.util.Arrays; // necessary to use the <Arrays> class public class Java1219 { public static void main (String args[]) { System.out.println("Java1219\n"); int list[] = {11,99,22,88,33,77,44,66,55}; System.out.println(Arrays.toString(list)); Arrays.sort(list); System.out.println(Arrays.toString(list)); System.out.println(); System.out.println("Index of 33 is " + Arrays.binarySearch(list,33)); System.out.println("Index of 11 is " + Arrays.binarySearch(list,11)); System.out.println("Index of 99 is " + Arrays.binarySearch(list,99)); System.out.println("Index of 10 is " + Arrays.binarySearch(list,10)); System.out.println("\n\n"); } } Java1219.java Output Java1219 [11, 99, 22, 88, 33, 77, 44, 66, 55] [11, 22, 33, 44, 55, 66, 77, 88, 99] Index Index Index Index of of of of 33 11 99 10 is is is is 2 0 8 -1 It was mentioned earlier that the whole point in sorting is the ability to search efficiently. In the case of the binary search sorting is not simply a matter of efficiency; it is a matter of accuracy. Once again you will appreciate this problem better when you actually implement a binary search yourself. It is easy to imagine that an unsorted list causes problems. Can you find a number in a phone book when the names are not sorted. You make the assumptions to move forward or backward in your search precisely because the phone book is alphabetized. Program Java1220.java, in figure 12.23, attempts to perform various searches on lists that are not properly sorted. The results are very inconclusive. In many cases a negative index is returned, when in fact the array element does exist. 12.38 Exposure Java, 2006 Edition 10-27-06 Figure 12.23 // Java1220.java // This program demonstrates that an array must be sorted before // the <binarySearch> method is called. Erroneous indexes are // returned if the list is not sorted. import java.util.Arrays; // necessary to use the <Arrays> class public class Java1220 { public static void main (String args[]) { System.out.println("Java1220\n"); int list[] = {11,99,22,88,33,77,44,66,55}; System.out.println(Arrays.toString(list)); System.out.println(); System.out.println("Index of 33 is " + Arrays.binarySearch(list,33)); System.out.println("Index of 11 is " + Arrays.binarySearch(list,11)); System.out.println("Index of 99 is " + Arrays.binarySearch(list,99)); System.out.println("Index of 10 is " + Arrays.binarySearch(list,10)); System.out.println("\n\n"); } } Java1220.java Output Java1220 [11, 99, 22, 88, 33, 77, 44, 66, 55] Index Index Index Index of of of of 22 33 66 88 is is is is 4 0 -10 -1 Class Arrays, Method binarySearch Method binarySearch searches the elements of an array object for a specified value. The index of the array element is returned, if the element is found and a negative index is returned otherwise. Array elements must be sorted, otherwise the binarySearch method returns incorrect information. int list[] = {11,99,22,88,33,77,44,66,55}; System.out.println("Index of 22 is " + Arrays.binarySearch(list,33)); Chapter XII Java Static Arrays 12.39 12.7 Input at the Command Line Prompt When you first started to look at Java program examples there were many statements that were initially not explained. The very first Java program presented to you used the following heading for the main method: public static void main(String args[ ]) It turns out that every program with a main method uses an array and I had little desire to explain arrays in the first Java chapter. Take a look at program Java1221.java, in figure 12.24. Figure 12.24 // Java1221.java // This program demonstrates how an argument can be entered from the // command line using the args[] array. This program expects a single argument. public class Java1221 { public static void main(String args[]) { System.out.println("Java1221\n"); System.out.print("Entered at command line: "); System.out.println(args[0]); } } Java1221.java Output 12.40 Exposure Java, 2006 Edition 10-27-06 You have never paid much attention to the information in the parameter list of the main method. It has always looked something like (String args[]). Smart student that you are, you realize that args is a one-dimensional array of String elements. For many programs args sits around chilling and receives little attention. But do not be deceived because the args array is paying close attention if any information is added at the command line prompt. It is a little confusing to appreciate this command line prompt business. You have been clicking icons on the JCreator IDE for months. It is possible provide input information at the time that a program is executed. This information is stored in the args array. You use the array identifier args with the appropriate index. In this case there is only one array element so access is done with a statement like System.out.println(args[o]); It will not be possible to execute any of the programs in this section correctly unless you make some setting changes in JCreator. After you perform the changes listed below, a window will pop up immediately after you execute a program. As soon as you enter the expected values, they are then assigned to the args array. Entering Command Line Values with JCreator If you use JCreator a small window pops up, which requests the main argument information. This window will only pop up in JCreator, if the following setting steps are used: Click Configure Click Options Click JDK Tools Select Run Application in the Select Tool Type window Click on default Click Edit Click the Parameters tab Check Prompt for main method arguments Click OK twice In all honesty this main argument feature is not used much. It is included in this array chapter to help clarify this (String args[]) parameter listing that you have observed in the main method heading for months now. That also means that you need to reverse the steps to make the main arguments window pop up. If you fail Chapter XII Java Static Arrays 12.41 to reverse the steps, you will have this window pop up every time. This will happen whether you have information to enter or not. The args array is not limited to a single value. You can enter multiple values at execution time, all separated by a space. Each value will be stored in the args array in the sequence that it is entered. Every value that is stored is treated like a string, even if a number is intended. You also need to keep in mind that a string of multiple words must be placed inside quotes, like "Hello World", to treat the two words as a single string. Program Java1222.java, in figure 12.25, enters three separate strings in the main arguments window, and you will note that each string is stored in a different array location. Figure 12.25 // Java1222.java // This program demonstrates how multiple arguments can be entered from the // command line using the args[] array. This program expects three separate // single arguments. public class Java1222 { public static void main(String args[]) { System.out.println("Java1222\n"); System.out.println("Entered at command line:\n"); System.out.println("args[0]: " + args[0]); System.out.println("args[1]: " + args[1]); System.out.println("args[2]: " + args[2]); } } Java1222.java Output 12.42 Exposure Java, 2006 Edition 10-27-06 Working Input with args The Java main method always includes (String args[ ]). The args array stores String values. There are many, many ways to do interactive input in Java. While the Scanner class will let you enter int and double values, the vast majority of Java input methods will only let you enter String values. It is possible to convert entered string values to numerical values by using Integer.parseInt and Double.parseDouble. Program Java1223.java, in figure 12.26 and program Java1224.java, in figure 12.27, demonstrate how to convert String input values to int values and to double values respectively. String values are converted to int values with Integer.parseInt and String values are converted to double values with Double.parseDouble. Figure 12.26 // Java1223.java // This program reviews the use of the <Integer> class with the <parseInt> // method to convert strings entered at the command line prompt to integers. public class Java1223 { public static void main(String args[]) { System.out.println("Java1223\n"); int nr1 = Integer.parseInt(args[0]); int nr2 = Integer.parseInt(args[1]); int sum = nr1 + nr2; System.out.println(nr1 + " + " + nr2 + " = " + sum); } } Java1223.java Output Chapter XII Java Static Arrays 12.43 Figure 12.27 // Java1224.java // This program reviews the use of the <Double> class with the <parseDouble> // method to convert strings entered at the command line prompt to real numbers. public class Java1224 { public static void main(String args[]) { System.out.println("Java1224\n"); double nr1 = Double.parseDouble(args[0]); double nr2 = Double.parseDouble(args[1]); double sum = nr1 + nr2; System.out.println(nr1 + " + " + nr2 + " = " + sum); } } The output for this program shall be shown including the Set main method arguments pop up window in JCreator. Figure 12.27 Continued Java1224.java Output 12.44 Exposure Java, 2006 Edition 10-27-06 12.8 Static Imports Java 5.0 has introduced a variety of features to make programming simpler. You have already seen several examples. The Scanner class provides easy keyboard input. The enhanced for..each loop simplifies access to data structure elements. This chapter will conclude with one more Java 5.0 feature. It is possible to use some special import statements, called static imports, which eliminate the need to use the class identifier when you call static classes. Program Java1225.java, in figure 12.28, looks at the System class. The program starts by demonstrating how the System class had to be used in previous Java versions, like Java 1.4. Yes, I know Java jumped from Java 1.4 to Java 5.0. They left off the 1. to make the name sound better. Using static imports is not very complicated. You do everything that you did previously, but now you can eliminate the System name. You do need to use the statement import static java.lang.System.*; to have access to this feature. Figure 12.28 // Java1225.java // STATIC IMPORTS #1 // This program introduces static imports. // With Java 5.0 it is now possible to use class methods without the class identifier. // In this example the <System> class name is not necessary. import static java.lang.System.*; // necessary to eliminate the <System> identifier public class Java1225 { public static void main (String args[]) { System.out.println("Java1225\n"); ///// JAVA 1.4 ///// System.out.println("This demonstrates Java 1.4"); System.out.println(); System.out.println("The static class identifier <System> must be used.\n\n"); ///// JAVA 5.0 ///// out.println("This demonstrates Java 5.0"); out.println(); out.println("It is not necessary to use the <System> class identifier.\n\n"); } } Java1225.java Output Java1225 This demonstrates Java 1.4 Chapter XII Java Static Arrays 12.45 The static class identifier <System> must be used. This demonstrates Java 5.0 It is not necessary to use the <System> class identifier. You know several other classes with static methods. The most common one is the Math class. Program Java1226.java, in figure 12.29, demonstrates the Math class along with the System class. For the Math class there is another import statement, import static java.lang.Math.*; that must be used. Figure 12.29 // Java1226.java // STATIC IMPORTS #2 // This program introduces more static imports. // In this example the <Math> and <System class names are not necessary. import static java.lang.System.*; import static java.lang.Math.*; // necessary to eliminate the <System> identifier // necessary to eliminate the <Math> identifier public class Java1226 { public static void main (String args[]) { System.out.println("Java1226\n"); ///// JAVA 1.4 ///// System.out.println("Math class methods are a good example of working with static imports."); System.out.println(); System.out.println("The square root of 100 is " + Math.sqrt(100)); System.out.println("13 to the 4th power is " + Math.pow(13,4)); System.out.println("\n\n"); ///// JAVA 5.0 ///// out.println("Math class methods are a good example of working with static imports."); out.println(); out.println("The square root of 100 is " + sqrt(100)); out.println("13 to the 4th power is " + pow(13,4)); out.println("\n\n"); } } Java1226.java Output Java1226 Math class methods are a good example of working with static imports. 12.46 Exposure Java, 2006 Edition 10-27-06 The square root of 100 is 13 to the 4th power is 10.0 28561.0 Math class methods are a good example of working with static imports. The square root of 100 is 13 to the 4th power is 10.0 28561.0 In this chapter you learned to use Arrays class methods. Arrays methods are static methods and once again you can use static imports to eliminate the use of the Arrays identifier. The import statement required for Arrays is import static java.util.Arrays.*; Figure 12.30 // Java1227.java // STATIC IMPORTS #3 // This program introduces more static imports. // In this example the <Arrays> and <System> class names are "sometimes" not necessary. import java.util.Arrays; // necessary to use the <Arrays> class import static java.lang.System.*; // necessary to eliminate the <System> identifier import static java.util.Arrays.*; // necessary to eliminate the <Arrays> identifier public class Java1227 { public static void main (String args[]) { System.out.println("Java1227\n"); int list[] = {12,56,34,91,65,27,45,70,85}; ///// JAVA 1.4 ///// System.out.println(Arrays.toString(list)); Arrays.sort(list); System.out.println(Arrays.toString(list)); System.out.println("\n\n"); ///// JAVA 5.0 ///// out.println(Arrays.toString(list)); sort(list); out.println(Arrays.toString(list)); out.println("\n\n"); // this is intentional; check next program // this is intentional; check next program } } Java1227.java Output Java1227 [12, 56, 34, 91, 65, 27, 45, 70, 85] Chapter XII Java Static Arrays 12.47 [12, 27, 34, 45, 56, 65, 70, 85, 91] [12, 27, 34, 45, 56, 65, 70, 85, 91] [12, 27, 34, 45, 56, 65, 70, 85, 91] This section will finish with an alert about static imports. You may run into situations where problems occur. Program Java1228.java, in figure 12.31, attempts to display array elements using the toString method. Surprisingly, the program does not compile. You see the unique situation where Java is confused. Method toString is a significant method used with many Java classes. The elimination of the class identifier Arrays, confuses Java. This program will not compile. The significance of the toString method in many Java classes will be explained in a later chapter. Figure 12.31 // Java1228.java // STATIC IMPORTS #4 // This program demonstrates a potential problem with static imports. // The <toString> method without the <Arrays> identifier confuses the Java compiler. // The <Object> class has a <toString> method, as do many other classes. // This program will not compile. import java.util.Arrays; // necessary to use the <Arrays> class import static java.lang.System.*; // necessary to eliminate the <System> identifier import static java.util.Arrays.*; // necessary to eliminate the <Arrays> identifier public class Java1228 { public static void main (String args[]) { System.out.println("Java1228\n"); int list[] = {12,56,34,91,65,27,45,70,85}; ///// JAVA 1.4 ///// System.out.println(Arrays.toString(list)); Arrays.sort(list); System.out.println(Arrays.toString(list)); System.out.println("\n\n"); ///// JAVA 5.0 ///// out.println(toString(list)); sort(list); out.println(toString(list)); out.println("\n\n"); } } 12.48 Exposure Java, 2006 Edition 10-27-06 Chapter XII Java Static Arrays 12.49 12.9 Summary This chapter introduced the concept of a data structure. It is important to realize that a data structure is more than some means to store data. The manner in which the data is accessed is an integral part of a data structure. The most common data structure in computer programming is the array. An array is a data structure with a fixed number of elements of the same type. Every element of the array can be accessed directly. Using arrays in Java requires that an array object be constructed with a specified type and a specified size. It is possible to initialize arrays with default values or values can be provided with the definition of an array. Integer arrays default to zero, character arrays default to the space character, and string arrays default to null. It is convenient to enter large sets of array values randomly. This can be done with a loop structure and the random method of the Math class. The random method can generate random real numbers and random integer values. It is also possible to generate random string values by using a random index of a string array to specify some unknown string value. Arrays can be declared for one, two or more dimensions. Each dimension requires its own index and access loop. One-dimensional arrays are also called vectors and two-dimensional arrays are called matrices. Access to array elements can be done with index access using the older for loop. It is also possible with the enhanced Java 5.0 for..each loop, which does not require an index value. The for..each loop cannot be used if one specific value needs to be accessed for processing. Elements in an array are processed with four common algorithms. Elements are displayed, entered, sorted and searched. There exist algorithms for each one of these processes. In this chapter the Arrays class is used with methods toString, fill, sort and binarySearch to perform array processing. Using these methods is done without knowledge of the algorithm implementation. The implementation of these methods will be learned in a later chapter. Input at the command line prompt was also explained by pointing out that the String args[] parameter listing in the main method is actually a String array waiting to store values that are entered at the start of program execution. All values entered in this manner are treated as strings. Any arithmetic processing requires that the strings be converted to number with parseInt or parseDouble. It 12.50 Exposure Java, 2006 Edition 10-27-06 is necessary to make changes to the IDE to enable main argument input. The settings for JCreator were shown, but keep in mind that the steps shown were JCreator dependent. Java 5.0 also introduces static imports. With the appropriate import statements it is possible to use standard class methods without the class identifier. This means that methods of the System, Math, Arrays and other static classes can be called without using the class identifier. Care needs to be taken that occasionally, a method may be called that causes confusion without the class identifier, because it exists in multiple classes. The toString method of the Arrays class is one example that requires the use of Arrays. Chapter XII Java Static Arrays 12.51 12.52 Exposure Java, 2006 Edition 10-27-06