Summary Section 7.1 Introduction • Arrays are fixed-length data structures consisting of related data items of the same type. Section 7.2 Arrays • An array is a group of variables (called elements or components) containing values that all have the same type. Arrays are objects, so they’re considered reference types. • A program refers to any one of an array’s elements with an array-access expression that includes the name of the array followed by the index of the particular element in square brackets ([]). • The first element in every array has index zero and is sometimes called the zeroth element. • An index must be a nonnegative integer. A program can use an expression as an index. • An array object knows its own length and stores this information in a length instance variable Section 7.3 Declaring and Creating Arrays • To create an array object, specify the array’s element type and the number of elements as part of an array-creation expression that uses keyword new. • When an array is created, each element receives a default value—zero for numeric primitive-type elements, false for boolean elements and null for references. • In an array declaration, the type and the square brackets can be combined at the beginning of the declaration to indicate that all the identifiers in the declaration are array variables. • Every element of a primitive-type array contains a variable of the array’s declared type. Every element of a reference-type array is a reference to an object of the array’s declared type. Section 7.4 Examples Using Arrays • A program can create an array and initialize its elements with an array initializer. • Constant variables are declared with keyword final, must be initialized before they’re used and cannot be modified thereafter. Section 7.5 Exception Handling: Processing the Incorrect Response • An exception indicates a problem that occurs while a program executes. The name “exception” suggests that the problem occurs infrequently—if the “rule” is that a statement normally executes correctly, then the problem represents the “exception to the rule.” • Exception handling enables you to create fault-tolerant programs. • When a Java program executes, the JVM checks array indices to ensure that they’re greater than or equal to 0 and less than the array’s length. If a program uses an invalid index, Java generates an exception to indicate that an error occurred in the program at execution time. • To handle an exception, place any code that might throw an exception in a try statement. • The try block contains the code that might throw an exception, and the catch block contains the code that handles the exception if one occurs. • You can have many catch blocks to handle different types of exceptions that might be thrown in the corresponding try block. • When a try block terminates, any variables declared in the try block go out of scope. • A catch block declares a type and an exception parameter. Inside the catch block, you can use the parameter’s identifier to interact with a caught exception object. • When a program is executed, array element indices are checked for validity—all indices must be greater than or equal to 0 and less than the length of the array. If an attempt is made to use an invalid index to access an element, an ArrayIndexOutOfRangeException exception occurs. • An exception object’s toString method returns the exception’s error message. Section 7.6 Case Study: Card Shuffling and Dealing Simulation • The toString method of an object is called implicitly when the object is used where a String is expected (e.g., when printf outputs the object as a String using the %s format specifier or when the object is concatenated to a String using the + operator). Section 7.7 Enhanced for Statement • The enhanced for statement allows you to iterate through the elements of an array or a collection without using a counter. The syntax of an enhanced for statement is: for (parameter : arrayName) statement where parameter has a type and an identifier (e.g., int number), and arrayName is the array through which to iterate. • The enhanced for statement cannot be used to modify elements in an array. If a program needs to modify elements, use the traditional counter-controlled for statement. Section 7.8 Passing Arrays to Methods • When an argument is passed by value, a copy of the argument’s value is made and passed to the called method. The called method works exclusively with the copy. Section 7.9 Pass-By-Value vs. Pass-By-Reference • When an argument is passed by reference, the called method can access the argument’s value in the caller directly and possibly modify it. • All arguments in Java are passed by value. A method call can pass two types of values to a method— copies of primitive values and copies of references to objects. Although an object’s reference is passed by value , a method can still interact with the referenced object by calling its public methods using the copy of the object’s reference. • To pass an object reference to a method, simply specify in the method call the name of the variable that refers to the object. • When you pass an array or an individual array element of a reference type to a method, the called method receives a copy of the array or element’s reference. When you pass an individual element of a primitive type, the called method receives a copy of the element’s value. • To pass an individual array element to a method, use the indexed name of the array. Section 7.11 Multidimensional Arrays • Multidimensional arrays with two dimensions are often used to represent tables of values consisting of information arranged in rows and columns. • A two-dimensional array with m rows and n columns is called an m-by-n array. Such an array can be initialized with an array initializer of the form arrayType[][] arrayName = {{row1 initializer}, {row2 initializer}, …}; • Multidimensional arrays are maintained as arrays of separate one-dimensional arrays. As a result, the lengths of the rows in a two-dimensional array are not required to be the same. • A multidimensional array with the same number of columns in every row can be created with an array-creation expression of the form arrayType[][] arrayName = new arrayType[numRows][numColumns]; Section 7.13 Variable-Length Argument Lists • An argument type followed by an ellipsis (...) in a method’s parameter list indicates that the method receives a variable number of arguments of that particular type. The ellipsis can occur only once in a method’s parameter list. It must be at the end of the parameter list. • A variable-length argument list is treated as an array within the method body. The number of arguments in the array can be obtained using the array’s length field. Section 7.14 Using Command-Line Arguments • Passing arguments to main from the command line is achieved by including a parameter of type String[] in the parameter list of main. By convention, main’s parameter is named args. • Java passes command-line arguments that appear after the class name in the java command to the application’s main method as Strings in the array args. Section 7.15 Class Arrays • Class Arrays provides static methods that peform common array manipulations, including sort to sort an array, binarySearch to search a sorted array, equals to compare arrays and fill to place items in an array. • Class System’s arraycopy method enables you to copy the elements of one array into another. Section 7.16 Introduction to Collections and Class ArrayList • The Java API’s collection classes provide efficient methods that organize, store and retrieve data without requiring knowledge of how the data is being stored. • An ArrayList<T> is similar to an array but can be dynamically resized. • The add method with one argument appends an element to the end of an ArrayList. • The add method with two arguments inserts a new element at a specified position in an ArrayList. • The size method returns the number of elements currently in an ArrayList. • The remove method with a reference to an object as an argument removes the first element that matches the argument’s value. • The remove method with an integer argument removes the element at the specified index, and all elements above that index are shifted down by one. • The contains method returns true if the element is found in the ArrayList, and false otherwise. |