Creating And Using Multidimensional Arrays


Creating And Using Single-Dimensional Arrays

This section shows you how to declare, create, and use single-dimensional arrays of both primitive and reference types. Once you know how a single-dimensional array works you can easily apply the concepts to multidimensional arrays.

Arrays Of Primitive Types

The elements of a primitive type array can be any of the Java primitive types. These include boolean, byte, char, short, int, long, float, and double. Example 8.1 shows an array of integers being declared, created, and utilized in a short program. Figure 8-4 shows the results of running this program.

Example 8.1: IntArrayTest.java

image from book
 1  public class IntArrayTest { 2    public static void main(String[] args){ 3       int[] int_array = new int[10]; 4       for(int i=0; i<int_array.length; i++){ 5          System.out.print(int_array[i] + " "); 6       } 7          System.out.println(); 8       } 9  }
image from book

image from book
Figure 8-4: Results of Running Example 8.1

Example 8.1 demonstrates several important concepts. First, an array of integer type having length 10 is declared and created on line 3. The name of the array is int_array. To demonstrate that each element of the array was automatically initialized to zero, the for statement on line 4 iterates over each element of the array beginning with the first element [0] and proceeding to the last element [9], and prints each element value to the console. As you can see from looking at figure 8-4 this results in all zeros being printed to the console.

Notice how each element of int_array is accessed via an index value that appears between square brackets appended to the name of the array. (i.e., int_array[i]) In this example the value of i is controlled by the for loop.

How Primitive Type Array Objects Are Arranged In Memory

Figure 8-5 shows how the integer primitive type array int_array declared and created in example 8.1 is represented in memory.

image from book
Figure 8-5: Memory Representation of Primitive Type Array int_array Showing Default Initialization

The name of the array, int_array, is a reference to an object in memory that has type “Array of int”. The array object is dynamically allocated in the heap with the new operator and its memory location is assigned to the int_array reference. At the time of array object creation each element is initialized to the default value for integers which is 0. The array object’s length attribute is initialized with the value of the length of the array which in this case is 10.

Let’s make a few changes to example 8.1 and assign some values to the int_array elements. Example 8.2 adds another for loop that initializes each element of int_array to the value of the for loop index variable i. Figure 8-6 shows the results of running this program.

Example 8.2: IntArrayTest.java (mod 1)

image from book
 1  public class IntArrayTest { 2    public static void main(String[] args){ 3       int[] int_array = new int[10]; 4       for(int i=0; i<int_array.length; i++){ 5          System.out.print(int_array[i] + " "); 6       } 7       System.out.println(); 8       for(int i=0; i<int_array.length; i++){ 9          int_array[i] = i; 10         System.out.print(int_array[i] + " ");  11      } 12      System.out.println(); 13    } 14  }
image from book

image from book
Figure 8-6: Results of Running Example 8.2

Notice on line 9 of example 8.2 how the value of the second for loop’s index variable i is assigned directly to each array element. When the array elements are printed to the console you can see that each element’s value has changed except for the first which is still zero.

Figure 8-7 shows the memory representation of int_array with its new element values.

image from book
Figure 8-7: Element Values of int_array After Initialization Performed by Second for Loop

Calling Object and Class Methods on Array References

Study the code shown in example 8.3 paying particular attention to lines 15 through 18.

Example 8.3: IntArrayTest.java (mod 2)

image from book
 1  public class IntArrayTest { 2    public static void main(String[] args){ 3       int[] int_array = new int[10]; 4       for(int i=0; i<int_array.length; i++){ 5          System.out.print(int_array[i] + " "); 6       } 7       System.out.println(); 8       for(int i=0; i<int_array.length; i++){ 9          int_array[i] = i; 10         System.out.print(int_array[i] + " "); 11      } 12      System.out.println(); 13 14      /***** Calling Object & Class Methods *****/ 15      System.out.println(int_array.getClass().getName()); 16      System.out.println(int_array.getClass().getSuperclass()); 17      System.out.println(int_array.getClass().isArray()); 18      System.out.println(int_array.getClass().isPrimitive()); 19    } 20  }
image from book

image from book
Figure 8-8: Results of Running Example 8.3

Lines 15 through 18 of example 8.3 above show how methods belonging to Object and Class can be used to get information about an array. The getClass() method belongs to java.lang.Object. It is used on each line to get the Class object associated with the array-type int[]. The getName(), getSuperClass(), isArray(), and isPrimitive() methods all belong to java.lang.Class.

The getName() method used on line 15 returns a String representing the name of the class. When this method is called it results in the characters “[I” being printed to the console. This represents the class name of an array of integers.

On line 16 the getSuperClass() method is called to get the name of int_array’s superclass. This results in the string “class java.lang.Object” being printed to the console indicating that the base class of int_array is Object. On line 17 the isArray() method is used to determine if int_array is an array. It returns the boolean value true as expected. The isPrimitive() method is used on line 18 to see if int_array is a primitive type. This returns a boolean false as expected since although int_array is an array of primitive types it is not itself a primitive type.

Creating Single-Dimensional Arrays Using Array Literal Values

Up to this point you have seen how memory for an array can be allocated using the new operator. Another way to allocate memory for an array and initialize the elements at the same time is to specify the contents of the array using array literal values. The length of the array is determined by the number of literal values appearing in the declaration. Example 8.4 shows two arrays being declared and created using literal values. Figure 8-9 shows the results of running this program.

Example 8.4: ArrayLiterals.java

image from book
 1  public class ArrayLiterals { 2    public static void main(String[] args){ 3      int[] int_array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; 4      double[] double_array = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0}; 5 6      for(int i = 0; i < int_array.length; i++){ 7         System.out.print(int_array[i] + " "); 8      } 9      System.out.println(); 10     System.out.println(int_array.getClass().getName()); 11     System.out.println(int_array.getClass().isArray()); 12 13     System.out.println(); 14 15     for(int i = 0; i < double_array.length; i++){ 16        System.out.print(double_array[i] + " "); 17     } 18     System.out.println(); 19     System.out.println(double_array.getClass().getName()); 20     System.out.println(double_array.getClass().isArray()); 21   } 22  }
image from book

image from book
Figure 8-9: Results of Running Example 8.4

Example 8.4 declares and initializes two arrays using array literal values. On line 3 an array of integer primitive types named int_array is declared. The elements of the array are initialized to the values that appear between the braces. Each element’s literal value is separated by a comma. The length of the array is determined by the number of literal values appearing between the braces. The length of int_array is 10.

On line 4 an array of double primitive types named double_array is declared and initialized with double literal values. The contents of both arrays are printed to the console. Object and Class methods are then used to determine the characteristics of each array and the results are printed to the console.

Differences Between Arrays Of Primitive Types And Arrays Of Reference Types

The key difference between arrays of primitive types and arrays of reference types is that primitive type values can be directly assigned to primitive type array elements. The same is not true for reference type elements. In an array of reference types, each element is a reference to an object in memory. When you create an array of references in memory you are not automatically creating each element’s object. Each reference element is automatically initialized to null and the object you want it to point to must be explicitly created. (Or the object must already exist somewhere in memory and be reachable.) To illustrate these concepts I will use an array of Objects. Example 8.5 gives the code for a short program that creates and uses an array of Objects. Figure 8-10 shows the results of running this program.

Example 8.5: ObjectArray.java

image from book
 1     public class ObjectArray { 2      public static void main(String[] args){ 3         Object[] object_array = new Object[10]; 4 5         object_array[0] = new Object(); 6         System.out.println(object_array[0].getClass()); 7         System.out.println(object_array[0].toString()); 8         System.out.println(); 9 10        object_array[1] = new Object(); 11        System.out.println(object_array[1].getClass()); 12        System.out.println(object_array[1].toString()); 13        System.out.println(); 14 15        for(int i = 2; i < object_array.length; i++){ 16            object_array[i] = new Object(); 17            System.out.println(object_array[i].getClass()); 18            System.out.println(object_array[i].toString()); 19            System.out.println(); 20        } 21     } 22    }
image from book

image from book
Figure 8-10: Results of Running Example 8.5

Referring to example 8.5, on line 3 an array of Objects of length 10 is declared and created. After line 3 executes the object_array reference will point to an array of Objects in memory with each element initialized to null as is shown in figure 8-11 below.

image from book
Figure 8-11: State of Affairs After Line 3 of Example 8.5 Executes

On line 5 a new Object object is created and its memory location is assigned to the Object reference located in object_array[0]. The memory picture now looks like figure 8-12 below. Lines 6 and 7 call the getClass() and the toString() methods on the object pointed to by object_array[0].

image from book
Figure 8-12: State of Affairs After Line 5 of Example 8.5 Executes.

The execution of line 10 results in the creation of another Object object in memory. The memory picture now looks like figure 8.13. The for statement on line 15 creates the remaining Object objects and assigns their memory locations to the remaining object_array reference elements. Figure 8.14 shows the memory picture after the for statement completes execution.

image from book
Figure 8-13: State of Affairs After Line 10 of Example 8.5 Executes

image from book
Figure 8-14: Final State of Affairs: All object_array Elements Point to an Object object

Now that you know the difference between primitive and reference type arrays let’s see some single-dimensional arrays being put to good use.

Single-dimensional Arrays In Action

This section offers several example programs showing how single-dimensional arrays can be used in programs. These programs represent an extremely small sampling of the usefulness arrays afford.

Message Array

One handy use for an array is to store a collection of String messages for later use in a program. Example 8.6 shows how such an array might be utilized. Figure 8-15 shows the results of running this program twice.

Example 8.6: MessageArray.java

image from book
 1     import java.io.*; 2      3     public class MessageArray { 4       public static void main(String[] args){ 5          BufferedReader console = new BufferedReader(new InputStreamReader(System.in)); 6          String name = null; 7          int int_val = 0; 8 9          String[] messages = {"Welcome to the Message Array Program", 10                              "Please enter your name: ", 11                              ", please enter an integer: ", 12                              "You did not enter an integer!", 13                              "Thank you for running the Message Array program", 14                              "Console read error!"}; 15 16         final int WELCOME_MESSAGE    = 0; 17         final int ENTER_NAME_MESSAGE = 1; 18         final int ENTER_INT_MESSAGE  = 2; 19         final int INT_ERROR          = 3; 20         final int THANK_YOU_MESSAGE  = 4; 21         final int CONSOLE_READ_ERROR = 5; 22 23       System.out.println(messages[WELCOME_MESSAGE]); 24       System.out.print(messages[ENTER_NAME_MESSAGE]); 25       try{ 26           name = console.readLine(); 27          }catch(Exception e){ System.out.println(messages[CONSOLE_READ_ERROR]); } 28 29       System.out.print(name + messages[ENTER_INT_MESSAGE]); 30 31       try{ 32           int_val = Integer.parseInt(console.readLine()); 33          }catch(NumberFormatException nfe) { System.out.println(messages[INT_ERROR]); } 34           catch(IOException ioe) { System.out.println(messages[CONSOLE_READ_ERROR]); } 35 36       System.out.println(messages[THANK_YOU_MESSAGE]); 37     } 38    }
image from book

image from book
Figure 8-15: Results of Running Example 8.6

Example 8.6 creates a single-dimensional array of Strings named messages. It initializes each String element using String literals. (Strings are given special treatment by the Java language and can be initialized using String literal values.) On lines 16 through 21 an assortment of constants are declared and initialized. These constants are used to index the messages array as is shown on lines 23 and 24.

The program simply asks the user to enter their name followed by a request for them to enter an integer value. Since the readLine() method may throw an IOException it must be enclosed in a try/catch block. Next, the user is prompted to enter an integer value. Now two things may go wrong. Either, the readLine() method may throw an IOEx-ception or the Integer.parseInt() method may throw a NumberFormatException. Notice the use of two catch blocks to check for each type of exception. Also notice in figure 8-15 the effects of entering a bad integer value.

Calculating Averages

The program given in example 8.7 will calculate class grade averages.

Example 8.7: Average.java

image from book
 1     import java.io.*; 2     import java.text.*; 3 4     public class Average { 5       public static void main(String[] args){ 6         BufferedReader console = new BufferedReader(new InputStreamReader(System.in)); 7         double[] grades = null; 8         double   total    = 0; 9         double   average  = 0; 10        int      grade_count = 0; 11        NumberFormat nf = NumberFormat.getInstance(); 12 13        nf.setMaximumFractionDigits(2); 14        System.out.println("Welcome to Grade Averager"); 15        System.out.print("Please enter the number of grades to enter: "); 16        try{ 17            grade_count = Integer.parseInt(console.readLine()); 18        } catch(NumberFormatException nfe) { System.out.println("You did not enter a number!"); } 19          catch(IOException ioe) { System.out.println("Problem reading console!"); } 20 21        if(grade_count > 0){ 22            grades = new double[grade_count]; 23            for(int i = 0; i < grade_count; i++){ 24                System.out.print("Enter grade " + (i+1) + ": "); 25                try{ 26                    grades[i] = Double.parseDouble(console.readLine()); 27                } catch(NumberFormatException nfe) { System.out.println("You did not enter a number!"); } 28                  catch(IOException ioe) { System.out.println("Problem reading console!"); } 29            } //end for 30 31 32            for(int i = 0; i < grade_count; i++){ 33                total += grades[i]; 34            } //end for 35 36            average = total/grade_count; 37            System.out.println("Number of grades entered: " + grade_count); 38            System.out.println("Grade average:                                                                                                                                                                        " + nf.format(average)); 39        }//end if 40      } //end main 41    }// end Average class definition
image from book

image from book
Figure 8-16: Results of Running Example 8.7

Referring to example 8.7 — an array reference of double primitive types named grades is declared on line 7 and initialized to null. On lines 8 through 10 several other program variables are declared and initialized. Take special note of what’s happening on line 11. Here a java.text.NumberFormat reference named nf is declared and initialized using the static method getInstance() provided by the NumberFormat class. Essentially, the NumberFormat class provides you with the capability to format numeric output in various ways. The NumberFormat reference nf is then used on line 13 to set the number of decimal places to display when writing floating point values. I have set the number of decimal places to 2 by calling the setMaximumFractionDigits() method with an argument of 2.

The program then prompts the user to enter the number of grades. If this number is greater than 0 then it is used on line 22 to create the grades array. The program then enters a for loop on line 23, reads each grade from the console, converts it to a double, and assigns it to the ith element of the grades array.

After all the grades are entered into the array the grades are summed in the for loop on line 32 and the average is calculated on line 36. Notice how the NumberFormat reference nf is used on line 38 to properly format the double value contained in the average variable.

Histogram: Letter Frequency Counter

Letter frequency counting is an important part of deciphering messages that were encrypted using monalphabetic substitution. Example 8.8 gives the code for a program that counts the occurrences of each letter appearing in a text string and prints a letter frequency display to the console. The program ignores all characters except the 26 letters of the alphabet. Figure 8-17 gives the results of running this program with a sample line of text.

Example 8.8: Histogram.java

image from book
 1     import java.io.*; 2 3     public class Histogram { 4       public static void main(String[] args){ 5         BufferedReader console = new BufferedReader(new InputStreamReader(System.in)); 6         int letter_frequencies[] = new int[26]; 7         final int A = 0, B = 1, C = 2, D = 3, E = 4, F = 5, G = 6, 8                   H = 7, I = 8, J = 9, K = 10, L = 11, M = 12, N = 13, 9                   O = 14, P = 15, Q = 16, R = 17, S = 18, T = 19, U = 20, 10                  V = 21, W = 22, X = 23, Y = 24, Z = 25; 11        String input_string = null; 12 13        System.out.print("Enter a line of characters: "); 14        try { 15            input_string = console.readLine().toUpperCase(); 16            } catch(IOException ioe) { System.out.println("Problem reading console!"); } 17 18        if(input_string != null){ 19          for(int i = 0; i < input_string.length(); i++){ 20            switch(input_string.charAt(i)){ 21             case 'A': letter_frequencies[A]++; 22                       break; 23             case 'B': letter_frequencies[B]++; 24                       break; 25             case 'C': letter_frequencies[C]++; 26                       break; 27             case 'D': letter_frequencies[D]++; 28                       break; 29             case 'E': letter_frequencies[E]++; 30                       break; 31             case 'F': letter_frequencies[F]++; 32                       break; 33             case 'G': letter_frequencies[G]++; 34                       break; 35             case 'H': letter_frequencies[H]++; 36                       break; 37             case 'I': letter_frequencies[I]++; 38                       break; 39             case 'J': letter_frequencies[J]++; 40                       break; 41             case 'K': letter_frequencies[K]++; 42                       break; 43             case 'L': letter_frequencies[L]++; 44                       break; 45             case 'M': letter_frequencies[M]++; 46                       break; 47             case 'N': letter_frequencies[N]++; 48                       break; 49             case 'O': letter_frequencies[O]++; 50                       break; 51             case 'P': letter_frequencies[P]++; 52                       break; 53             case 'Q': letter_frequencies[Q]++; 54                       break; 55             case 'R': letter_frequencies[R]++; 56                       break; 57             case 'S': letter_frequencies[S]++; 58                       break; 59             case 'T': letter_frequencies[T]++; 60                       break; 61             case 'U': letter_frequencies[U]++; 62                       break; 63             case 'V': letter_frequencies[V]++; 64                       break; 65             case 'W': letter_frequencies[W]++; 66                       break; 67             case 'X': letter_frequencies[X]++; 68                       break; 69             case 'Y': letter_frequencies[Y]++; 70                       break; 71             case 'Z': letter_frequencies[Z]++; 72                       break; 73             default : 74             } //end switch 75            } //end for 76 77         for(int i = 0; i < letter_frequencies.length; i++){ 78            System.out.print((char)(i + 65) + ": "); 79            for(int j = 0; j < letter_frequencies[i]; j++){ 80             System.out.print('*'); 81            } //end for 82            System.out.println(); 83        } //end for 84 85       } //end if 86      } // end main 87     } // end Histogram class definition
image from book

image from book
Figure 8-17: Results of Running Example 8.8

Referring to example 8.8 — on line 6 an integer array named letter_frequencies is declared and initialized to contain 26 elements, one for each letter of the alphabet. On lines 7 through 10 several constants are declared and initialized. The constants, named A through Z, are used to index the letter_frequencies array later in the program. On line 11 a String reference named input_string is declared and initialized to null.

The program then prompts the user to enter a line of characters. The program reads this line of text and converts it all to upper case using the toUpperCase() method of the String class. Most of the work is done within the body of the if statement that starts on line 18. If the input_string is not null then the for loop will repeatedly execute the switch statement, testing each letter of input_string and incrementing the appropriate letter_frequencies element.

Take special note on line 19 of how the length of the input_string is determined using the String class’s length() method. A String object is not an array but the methods length() and charAt() allow a String object to be manipulated on a read-only basis in similar fashion.

Quick Review

Single-dimensional arrays have one dimension — length. You can get an array’s length by accessing its length attribute. Arrays can have elements of primitive or reference types. An array type is created by specifying the type name of array elements followed by one set of brackets [ ]. Use the java.lang.Object and java.lang.Class methods to get information about an array.

Each element of an array is accessed via an index value contained in a set of brackets. Primitive-type element values can be directly assigned to array elements. When an array of primitive types is created each element is initialized to a default value that’s appropriate for the element type. Each element of an array of references is initialized to null. Each object each reference element points to must be dynamically created at some point in the program.




Java For Artists(c) The Art, Philosophy, and Science of Object-Oriented Programming
Java For Artists: The Art, Philosophy, And Science Of Object-Oriented Programming
ISBN: 1932504052
EAN: 2147483647
Year: 2007
Pages: 452

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net