Reserved. 6.1 Introduction (cont.) At the end of this chapter, we introduce one of Java’s prebuilt data structures from the Java API’s collection classes. ◦ Greater capabilities than traditional arrays. ◦ Reusable, reliable, powerful and efficient. ◦ Focus on the ArrayList collection. ArrayLists are similar to arrays but provide additional functionality, such as dynamic resizing as necessary to accommodate more or fewer elements. After reading Chapter 17, Lambdas and Streams, you’ll be able to reimplement many of Chapter 6’s examples in a more concise and elegant manner, and in a way that makes them easier to parallelize to improve performance on today’s multi-core systems.
Reserved. 6.2 Primitive Types vs. Reference Types (cont.) A primitive-type variable can hold exactly one value of its declared type at a time. Programs use variables of reference types (normally called references) to store the addresses of objects in the computer’s memory. ◦ Such a variable is said to refer to an object in the program. To call an object’s methods, you need a reference to the object. If an object’s method requires additional data to perform its task, then you’d pass arguments in the method call. Primitive-type variables do not refer to objects, so such variables cannot be used to invoke methods.
Reserved. 6.3 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. Elements can be either primitive types or reference types. To refer to a particular element in an array, we specify the name of the reference to the array and the position number of the element in the array. ◦ The position number of the element is called the element’s index or subscript.
Reserved. 6.3 Arrays (cont.) Every array object knows its own length and stores it in a length instance variable. Even though the length instance variable of an
array is public, it cannot be changed because it’s a
Reserved. 6.5 Examples Using Arrays This section presents several examples that demonstrate declaring arrays, creating arrays, initializing arrays and manipulating array elements.
Reserved. 6.5.1 Creating and Initializing an Array The application of Fig. 6.2 uses keyword new to create an array of 10 int elements, which are initially zero (the default initial value for int variables).
Reserved. 6.5.7 Using Arrays to Analyze Survey Results (Cont.) The last value in the array is intentionally an incorrect response (14). When a Java program executes, 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. Any attempt to access an element outside that range of indices results in a runtime error that’s known as an ArrayIndexOutOfBoundsException. We use the six-element array frequency to count the number of occurrences of each response.
Reserved. 6.6.1 The try Statement 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. The braces that delimit the bodies of the try and catch blocks are required.
Reserved. 6.6.2 Executing the catch Block When the program encounters the invalid value 14 in the responses array, it attempts to add 1 to frequency[14], which is outside the bounds of the array—the frequency array has only six elements (with indexes 0–5). Because array bounds checking is performed at execution time, the JVM generates an exception— specifically an ArrayIndexOutOfBoundsException to notify the program of this problem. At this point the try block terminates and the catch block begins executing—any local variables declared in the try block are now out of scope (and no longer exist), so they’re not accessible in the catch block.
Reserved. 6.6.3 toString Method of the Exception Parameter When the exception is caught, the program displays a message indicating the problem that occurred. We implicitly call the exception object’s toString method to get the error message that’s implicitly stored in the exception object and display it. Once the message is displayed in this example, the exception is considered handled and the program continues with the next statement after the catch block’s closing brace. In this example, the end of the for statement is reached, so the program continues with the increment of the control variable in the for header .
Reserved. 6.7 Enhanced for Statement Iterates through the elements of an array without using a counter, thus avoiding the possibility of “stepping outside” the array. Syntax: for (parameter : arrayName) statement ◦ where parameter has a type and an identifier, and arrayName is the array through which to iterate. ◦ Parameter type must be consistent with the type of the elements in the array.
Reserved. 6.7 Enhanced for Statement (Cont.) Figure 6.9 uses the enhanced for statement to sum the integers in an array of student grades. Can be used only to obtain array elements—it cannot be used to modify elements. Can be used in place of the counter-controlled for statement whenever code looping through an array does not require access to the counter indicating the index of the current array element.
Reserved. 6.8 Passing Arrays to Methods (Cont.) When an argument to a method is an entire array or an individual array element of a reference type, the called method receives a copy of the reference. However, when an argument to a method is an individual array element of a primitive type, the called method receives a copy of the element’s value. Such primitive values are called scalars or scalar quantities. To pass an individual array element to a method, use the indexed name of the array element as an argument in the method call.
Reserved. 6.8 Passing Arrays to Methods (cont.) Figure 6.10 demonstrates the difference between passing an entire array and passing a primitive-type array element to a method. Method modifyArray receives a copy of array’s
reference and uses the reference to multiply each of
array’s elements by 2. When a copy of an individual primitive-type array
element is passed to a method, modifying the copy
in the called method does not affect the original value of that element in the calling method’s array.
Reserved. 6.9 Pass-By-Value vs. Pass-By-Reference (Cont.) Java does not allow you to choose pass-by-value or pass- by-reference—all arguments 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. ◦ Objects themselves cannot be passed to methods. If you modify a reference-type parameter so that it refers to another object, only the parameter refers to the new. 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. ◦ The parameter in the called method and the argument in the calling method refer to the same object in memory.
Reserved. 6.10 Multidimensional Arrays (cont.) Figure 6.11 illustrates a two-dimensional array named a with three rows and four columns (i.e., a three-by-four array). In general, an array with m rows and n columns is
Reserved. 6.10 Multidimensional Arrays (cont.) Figure 6.12 demonstrates initializing two- dimensional arrays with array initializers, and using nested for loops to traverse the arrays—that is, manipulate every element of each array.
Reserved. 6.14 Introduction to Collections and Class ArrayList Collections provide efficient methods that organize, store and retrieve your data without requiring knowledge of how the data is being stored. The collection class ArrayList<T> (package java.util) can dynamically change its size to accommodate more elements. The T (by convention) is a placeholder—when declaring a new ArrayList, replace it with the type of elements that you want the ArrayList to hold.
Reserved. 6.14 Introduction to Collections and Class ArrayList (Cont.) Classes with this kind of placeholder that can be used with any type are called generic classes. Figure 6.16 shows some common methods of class ArrayList<T>.
Reserved. 6.14 Introduction to Collections and Class ArrayList (Cont.) The preceding statement can be written as: ArrayList<String> items = new ArrayList<>(); When the compiler encounters the diamond (<>) in the class instance creation expression, it uses the declaration of variable items to determine the ArrayList’s element type (String)—this is known as inferring the element type.