All Rights Reserved. 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. Java SE 8 ◦ After reading Chapter 17, Java SE 8 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.
All Rights Reserved. Java’s types are divided into primitive types and reference types. ◦ Primitive types: boolean, byte, char, short, int, long, float and double. All nonprimitive types are reference types.
All Rights Reserved. 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.
All Rights Reserved. Like other objects, arrays are created with keyword new. To create an array object, you specify the type of the array elements and the number of elements as part of an array-creation expression that uses keyword new. ◦ Returns a reference that can be stored in an array variable. The following declaration and array-creation expression create an array object containing 12 int elements and store the array’s reference in the array variable named c: int[] c = new int[12]; The square brackets following the type indicate that the variable will refer to an array.
All Rights Reserved. This section presents several examples that demonstrate declaring arrays, creating arrays, initializing arrays and manipulating array elements.
All Rights Reserved. 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).
All Rights Reserved. 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.
All Rights Reserved. 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.
All Rights Reserved. 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 line 19 throws 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.
All Rights Reserved. When lines 21–26 catch the exception, the program displays a message indicating the problem that occurred. Line 23 implicitly calls 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 (line 27), so the program continues with the increment of the control variable in line 15.
All Rights Reserved. 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.
All Rights Reserved. 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.
All Rights Reserved. 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.
All Rights Reserved. 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.
All Rights Reserved. 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.
All Rights Reserved. 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
All Rights Reserved. A multidimensional array with the same number of columns in every row can be created with an array-creation expression, as in: int[][] b = new int[3][4]; Programs can also use variables to specify array dimensions, because new creates arrays at execution time—not at compile time. The elements of a multidimensional array are initialized when the array object is created. A multidimensional array in which each row has a different number of columns can be created as follows: int[][] b = new int[2][ ]; // create 2 rows b[0] = new int[5]; // create 5 columns for row 0 b[1] = new int[3]; // create 3 columns for row 1
All Rights Reserved. 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.
All Rights Reserved. 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.
All Rights Reserved. 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>.
All Rights Reserved. In Java SE 7 and higher, 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.
All Rights Reserved. Using Java’s graphics features, we can create complex drawings that would be more tedious to code line by line. In Figs. 6.18-6.19, we use arrays and repetition statements to draw a rainbow by using Graphics method fillArc. Drawing arcs in Java is similar to drawing ovals—an arc is simply a section of an oval. The colors of a rainbow are red, orange, yellow, green, blue, indigo and violet. Java has predefined constants only for the first five colors. Lines 15–17 initialize an array with the colors of the rainbow, starting with the innermost arcs first.
All Rights Reserved. The fillArc method draws a filled arc. Method fillArc requires six parameters. ◦ The first four represent the bounding rectangle in which the arc will be drawn. ◦ The first two of these specify the coordinates for the upper-left corner of the bounding rectangle, and the next two specify its width and height. ◦ The fifth parameter is the starting angle on the oval, and the sixth specifies the sweep, or the amount of arc to cover. ◦ The starting angle and sweep are measured in degrees, with zero degrees pointing right. ◦ A positive sweep draws the arc counterclockwise. ◦ Method drawArc requires the same parameters as fillArc, but draws the edge of the arc rather than filling it.