Chapter 6 SINGLE-DIMENSIONAL ARRAYS Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk
What is an Array? A single array variable can reference a large collection of data. Arrays have three important properties: arrays represent a group of related data (for example, temperature for the last five days, or stock prices for the last 30 days.) all data within a single array must share the same data type (for example, you can create an array of ints or an array of floats, but you cannot mix and match ints with floats.) The size of an array is fixed once it is created.
What exactly are we talking about?! Let s say you have ten students and you want to save the grades for each of them for use throughout your program (i.e. we need to remember every grade not just loop and count them or average them, etc.) Could do it the hard way: Set up ten variables called studentonegrade, studenttwograde, studentthreegrade, etc. Very difficult to use and manipulate Instead, could use an array to do it the easy way
Using an array variable Create an array variable called studentgrades[10] Declared as follows: int studentgrades[] = new int[10]; This sets up a location in memory for 10 integers which can be referenced using studentgrades[ [ # ] where # is the particular student you want to look at.
Array Naming Considerations The rules for naming variables apply when selecting array variable names Composed of letters, digits, dollar signs and underscore characters Cannot start with a digit Follow all the good programming hints recommended for variable names i.e. just think of it as an ordinary variable when making up the name In addition it is bad style to end an array name with a digit ie. array3[5]
Parts of the array The array has some terminology we haven t seen yet Elements Index Position Number Subscript Zeroth element Keyword new
Elements Refers to the individual items represented by the array. For example, an array of 10 integers is said to have 10 elements an array of 15 floats has 15 elements an array of 5 characters has 5 elements and so on
Index (Position Number or Subscript) Refers to one particular element in the array Also known as position number or, more formally, as a subscript The first element in an array is represented by an index or subscript of 0 (zero). For example, studentgrades[ [ 0 ] This first position is known as the zeroth element The second position is referred to by studentgrades[ [ 1 ]
Figuring out the array positions In Java, an arrays elements start out at index 0 and go up to (the number of elements 1) For example, our array of 10 student grades filled in with grades might look like: Index 0 1 2 3 4 5 6 7 8 9 Value 85 76 99 38 78 98 89 90 82 88
Array positions (cont d) We can access them by specifying the array name followed by square brackets with the index number between them. For example, System.out.println ("The third student s s grade is " + studentgrades[ [ 2 ] ); Would print only the third integer spot in the array (remember 0 is the first, 1 is the second, and 2 is the third element s index / subscript) The output would look like the following: The third student s grade is 99
Array positions (cont d) The index scheme starting at 0 may be initially confusing. This is the cause of many off-by-one errors so study the concept carefully The element in the array s first position is sometimes referred to as the zeroth element. Notice the difference between "position" and "element number"
subscript terminology From this point forward, for this class, all references to array elements will refer to the subscript of the array. In the event that we want to discuss the position of an element in an array, we will refer to it s position. In other words, we will not use i'th element or element i notation unless we are referring to the zeroth element.
Keyword new As we will see, the keyword new is used in Java when you wish to create a new object. In Java, arrays are objects. As with all data members of objects, the elements of the each position in a new array will automatically be initialized to the default value for the array s type.
Some powerful features of arrays Can use expressions as the subscript E.g. if variables a = 1 and b = 2 studentgrades[ [ a + b ] would be the same as writing studentgrades[ [ 3 ] Can use array elements in expressions E.g. int gradetotal = 0 ; gradetotal = studentgrades[ [ 0 ] + studentgrades[ [ 1 ] + studentgrades[ [ 2 ] + etc studentgrades[ [ 9 ] ; Would add up all the array elements and store them in gradetotal.
Powerful features (cont d) Can set array elements equal to other values or expressions. For example, studentgrades[ [ 1 ] = 100 ; This would set the array element with a subscript of 1 to a grade of 100. That is, the second student would have a grade of 100. Java allows us to access an array s length by using the following notation: studentgrades.length would evaluate to 10
So how do we use arrays? Same concepts as other variables apply Must declare the array Must initialize the array (unlike regular variables, Java will automatically initialize arrays with default values) Arrays variables are actually reference variables. Can use arrays in expressions and methods, setting elements values or using their values, similar to the use of ordinary variables
Declaring an array First you can declare an array reference variable (you must specify the type of the elements in the array) : int [] myfirstarray; //declares an array //variable for ints Note: the line above does not allocate memory for the array (it cannot since we have not said the size of the array yet). It only sets aside enough memory to reference the array. Until we create an array, the reference is to null. Next, we create the array and point the reference to it: myfirstarray = new int [10]; To create the array, we need the number of elements in the array so the computer can set aside adequate memory for the array. We can combine the declaration and allocation lines into one line as follows: int [] myfirstarray = new int [10];
Initializing array with a for loop After declaring an array, you can initialize it in the body of your program by using a for loop: int [] myfirstarray = new int [ 5 ]; for (int( i = 0 ; i <= 4 ; i++ ) { myfirstarray[ [ i ] = 1 ; } // end for Note the upper bound is 4, not 5! That is, you loop through 0 to 4 to initialize an array with 5 elements Note: Array elements are initialized with default values. Numeric types get 0, boolean get false and char gets the null character (ascii code 0).
Declaring arrays (cont) You can use a constant to set the size of the array final int NUM_STUDENTS_IN_CLASS = 8 int [] exams = new int [NUM_STUDENTS_IN_CLASS ]; In Java, you do not need to know the size of the array at COMPILE time. Instead you can know the size at RUN time. For example, the following is legal: inputstring = JOptionPane.showInputDialog ("How many students?"); int students = Integer.parseInt (inputstring); int [] myfirstarray = new int [students];
Initializing an Array You can initialize an array when you declare it, as you do with other variables Syntax is slightly different, as you are now initializing more than one element at a time One way at declaration, using initializers: int myfirstarray[ [ ] = { 0, 0, 0, 0, 0 }; Note the braces around the initial zeroes which themselves are separated by commas. Also note that creating arrays in this way eliminates the need for the keyword new.
Accessing elements with for loop Can use a for loop to print the contents of an array int [] myfirstarray = new int [ 5 ]; for (int( i = 0 ; i <= myfirstarray.length 1; i++ ) { System.out.println ("array element " + i + " is equal to " + myfirstarray [i]); } // end for For an array of the char[ ] type, it can be printed using one print statement. For example, the following code displays IYAD : char[ ] name = { I {, Y, A, D }; System.out.println(name);
for-each Loops Outline In general, the syntax for a for-each loop is for (elementtype( element: arrayrefvar) ) { } // Process the element For example, the following code displays all the elements in the array mylist : for(double u: mylist) { System.out out.println(u); } 2003 Prentice Hall, Inc. All rights reserved.
Array Bounds Very Important: Java does not provide array bounds checking at compile time. This means that your program will crash at run time of you try to access memory outside of an array s bounds. For example, suppose you have: int [] myfirstarray = new int [ 10 ]; myfirstarray[100] = 45; 100 is very far outside your defined size (0..9) However, the compiler will not indicate an error.
Outline Example Using Arrays Using histograms do display array data graphically Histogram Plot each numeric value as bar of asterisks (*) 2003 Prentice Hall, Inc. All rights reserved.
1 // Histogram.java 2 // Histogram printing program. 3 import javax.swing.*;.*; 4 5 public class Histogram { 6 Declare array with initializer list 7 public static void main( String args[] ) 8 { 9 int array[] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 }; 10 11 String output = "Element\tValue tvalue\thistogram thistogram"; 12 13 // for each array element, output a bar in histogram 14 for ( int counter = 0; counter < array.length; counter++ ) { 15 output += "\n" + counter + "\t" + array[ counter ] + "\t" t"; 16 17 // print bar of asterisks 18 for ( int stars = 0; stars < array[ counter ]; stars++ ) 19 output += "*"; 20 21 } // end outer for 22 23 JTextArea outputarea = new JTextArea(); 24 outputarea.settext( output ); 25 For each array element, print associated number of asterisks Outline Histogram.java Line 9 Declare array with initializer list Line 19 For each array element, print associated number of asterisks 2003 Prentice Hall, Inc. All rights reserved.
26 JOptionPane.showMessageDialog( null, outputarea, 27 "Histogram Printing Program", JOptionPane.INFORMATION_MESSAGE ); 28 29 System.exit( 0 ); 30 31 } // end main 32 33 } // end class Histogram Outline Histogram.java 2003 Prentice Hall, Inc. All rights reserved.
References and Reference Parameters Outline Two ways to pass arguments to methods Pass-by-value Copy of argument s value is passed to called method In Java, every primitive is pass-by-value Pass-by-reference Caller gives called method direct access to caller s data Called method can manipulate this data Improved performance over pass-by-value In Java, every object is simulated pass-by-reference In Java, arrays are objects Therefore, arrays are passed to methods by reference Technically, we are using pass by value but the value we are passing is a reference to the array. 2003 Prentice Hall, Inc. All rights reserved.
Passing Arrays to Methods Outline To pass array argument to a method Specify array name without brackets Array hourlytemperatures is declared as int [ ] mylist ={1,2,3,4}; The method call printarray( mylist ); Or printarray( ( new int[]{1,2,3,4} ); 2003 Prentice Hall, Inc. All rights reserved.
Passing arrays to methods (cont) In the method header, use similar syntax as that for array declaration: public static void printarray (int array [] ) or public static void ptintarray (int [] array ) For example, the following method displays the elements in an int array: Public static void printarray(int [] array){ for(int i=0 ; i < array.length ; ++i) system.out.println( array[i] ] + ); }
Example for pass by sharing Outline Public class Test{ } } public static void main (String [ ] args){ int x=1; int [ ] y = new int [10]; m( x, y ); System.out.println( x is + x); System.out.println( y[0] y[0] is + y[0] ); public static void m( int number, int [ ] numbers){ } number = 1001; numbers[0] = 5555; X is 1 Y[0] is 5555 2003 Prentice Hall, Inc. All rights reserved.
Outline Example for pass by sharing, cont. The primitive type value in x is passed to number, and the reference value in y is passed to numbers. 2003 Prentice Hall, Inc. All rights reserved.
Returning arrays from methods We have seen examples of methods that modify an array. Since the array is passed by reference, it is modified in the original method as well. Another way to return information in an array is to explicitly return the array. For example, a method with the header: public static int [] makearray () Returns an integer array.
Returning arrays (cont) In order to return an array, the method creates the array first. public static int [] makearray () { int [] myarray = new int [10]; for (int( i; i < myarray.length; i++) Myarray [i] = i; return myarray; } The method above creates a new array called myarray, initializes each element and returns the reference to myarray.
Returning arrays (cont) Outline For example, the following method returns an array that is the reversal of another array. For example, the following statement returns a new array list2 with elements 6,5,4,3,2,1 Int [ ] list1={1,2,3,4,5,6}; Int [ ] list2= reverse(list1); 2003 Prentice Hall, Inc. All rights reserved.
Outline Variable-Length Argument Lists A variable number of arguments of the same type can be passed to a method and treated as an array. You can pass a variable number of arguments of the same type to a method. The parameter in the method is declared as follows: typename... parametername Example: 2003 Prentice Hall, Inc. All rights reserved.
Example of Copying Arrays In this example, you will see that a simple assignment cannot copy arrays in the following program. The program simply creates two arrays and attempts to copy one to the other, using an assignment statement.
Copying Arrays Before the assignment list2 = list1; After the assignment list2 = list1; list1 Contents of list1 list1 Contents of list1 list2 Contents of list2 list2 Garbage Contents of list2
Copying Arrays Using a loop: int[] sourcearray = {2, 3, 1, 5, 10}; int[] targetarray = new int[sourcearray.length]; for (int( i = 0; i < sourcearrays.length; ; i++) targetarray[i] ] = sourcearray[i];
The arraycopy Utility arraycopy(sourcearray, src_pos, targetarray, tar_pos,, length); Example: System.arraycopy(sourceArray,, 0, targetarray, 0, sourcearray.length);
The Arrays Class Outline The java.util.arrays class contains useful methods for common array operations such as sorting and searching. For example, the following code sorts an array of numbers and an array of characters. double[ ] numbers = {6.0,4.4,1.9,2.9,3.4,3.5 }; java.util.arrays.sort(numbers); // Sort the whole array char[ ] chars = { a {, A, 4, F, D, P }; java.util.arrays.sort(chars,1, 3);// Sort part of the array from chars[1] to chars[3-1]. 2003 Prentice Hall, Inc. All rights reserved.
The Arrays Class, cont. Outline For example, the following code searches the keys in an array of integers and an array of characters. int[ [] list = {2, 4, 7, 10, 11, 45, 50, 59, 60, 66, 69, 70, 79}; System.out.println( (1) (1) Index is +java.util util.arrays.binarysearch(list,11 )); System.out.println( (2) (2) Index is +java.util util.arrays.binarysearch(list,12 )); char [ ] chars = { a,{ c, g, x, y, z }; System.out.println( (3) (3) Index is +java.util util.arrays.binarysearch(chars, chars, a )); System.out.println( (3) (3) Index is +java.util util.arrays.binarysearch(chars, chars, t )); The output of the preceding code is 1. Index is 4 2. Index is 6 3. Index is 0 4. Index is 4 2003 Prentice Hall, Inc. All rights reserved.