Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 5 Arrays A way to organize data. What are Arrays? An array is a named list of data values that all have the same type An array is a collection.

Similar presentations


Presentation on theme: "Lecture 5 Arrays A way to organize data. What are Arrays? An array is a named list of data values that all have the same type An array is a collection."— Presentation transcript:

1 Lecture 5 Arrays A way to organize data

2 What are Arrays? An array is a named list of data values that all have the same type An array is a collection of data values of the same type. An array is a series of compartments to store data. Each compartment is appropriately sized for the particular data type the array is declared to store. For instance, we may declare an array of float, but not an array of both int and float An array can hold only one type of data! E.g. int[] can hold only integers char[] can hold only characters

3 Array Visualization sizes[0] int[] sizes = new int[10]; Specifies an array of variables of type int // An array of 10 integers index values We are creating a new array object The array reference variable The array object is of type int and has ten elements sizes[1]sizes[2]sizes[3]sizes[4]sizes[9] 305136411227 Element value at index 2

4 Declaring an Array Variable In Java, an array variable is declared in the same way any variable is declared, but with a set of square brackets after the specified data type of the array To use an array in a program, a variable to reference the array must be declared, and specify the type of array the variable can reference General syntax for array declaration is shown below. datatype[] arrayName; For example, an array of integers called prices and an array of String called names are declared below: int[] prices; String[] names;

5 Creating a New "Empty" Array When an array variable is created, memory space is still required to store the array elements or values In Java, arrays are objects so we need to use the same method as we create objects to actually create an array. for example new int[20]; The new keyword creates an array of type int of size 20 The array can then be assigned to an array variable or an array object as in the example below: int[] prices = new int[20]; Like any other object we can declare and create an array in one statement as the following example shows float[] prices = new float[20] When first created as above, the items in the array are initialized to the default value of the data type int: 0 double: 0.0 String: null

6 Array Indices A single identifier is used to refer to an array of values Each individual value is called an element of the array Each array element can be distinguished from other elements by an assigned integer reference number. The integer reference number is called the index of the array element and is usually inside the square brackets In Java, the array index must be an integer or an integer expression The index is also known as a subscript of array elements Important: In Java (and most other languages), the index starts from 0 and ends at n-1, where n is the size of the array

7 Arrays as References A variable that has the primitive type holds value in computer memory A variable that has a reference type such as an array holds a memory address for storing values Array names represent memory addresses/locations Array names contain references just as other Java objects When an array name is declared no memory address is assigned to it The default value for an uninitialised array is null As an example the array declared as int [] ages; has the default value null

8 Initialising Array Elements When the keyword new is used to define an array, the name of the array is given a value that represents a computer memory address In the expression below a memory address is assigned to the array named ages: int[] ages = new int[5]; In the declaration int[] ages = new int[5]; each element has a default value of 0 because ages is a numeric array Each element can then be assigned a value by the expression ages[0] = 6; The default for char is ‘\u0000’ and false for boolean.

9 Assigning Values to array elements Array elements can be assigned non default values when they are created Array initialisation is done by separating the values with commas within a pair of curly brackects An array called primes which holds the first five prime numbers can be declared and initialised as follows int[ ] primes = { 1, 3, 5, 7, 11 }; Note that the compiler can determine the size of the array by the number of elements in the initialising list In the above declaration, the array has 5 elements, thus the array size is 5 New memory is assigned based on the length of the list

10 Filling an Array An array can be declared and filled with values in subsequent statements Assigning values to individual elements is also known as populating the array An array declared as double[ ] prices ; can be filled as shown below prices[0] = 6.75; prices[1] = 80.43; prices[2] = 10.02;

11 Constructing Arrays  To construct an array, you can declare a new empty array and then assign values to each of the elements: String[] names = new String[5]; // String array  They can be assigned values as follows names[0] = “Kojo”; names[1] = “Kobina”; names[2] = “Ekuwa”; names[3] = “Baaba”; names[4] = “Alhassana”;  The above is method is used to assign values to the array names in two steps

12 Declaring and Initializing Arrays You can also specify all of the items in an array at its creation. Use curly brackets to surround the array’s data and separate the values with commas: String[] banks = { “Barclays”, “NIB”, “Stanbic”, “ADB”, “HFC”, “GTBank”, “UT Bank”, “GCB” }; Note that all the items must be of the same type. Here they are of type String. Another example: int[] powers = {0, 1, 10, 100};

13 Declaring and Initializing Arrays contd The general syntax for declaring and initialising arrays is given as follows datatype[ ] arrayRefVariable = { element1, element2, …. elementi }; An example is double[ ] arr1 = { 2.5, 6.3, 4.7, 8.0 }; Note that the new operator is not required in the array initializer syntax The above declaration is equivalent to declaration below double[ ] arr1 = new double[ 4 ]; arr1[ 0 ] = 2.5; arr1[ 1 ] = 6.3; arr1[ 2 ] = 4.7; arr1[ 3 ] = 8.0;

14 Initializing arrays In using the array initialization syntax, please note that we must declare, create and initialise the array in just one statement Splitting it would result in an error The following statement is wrong double[ ] arr1; arr1 = { 2.5, 6.3, 4.7, 8.0 }; Arrays can be declared using the following syntax new dataType[ ] { element1, element2, …., Elementi }; The following statements are correct int[] arr2 = { 10, 4, 67 }; We can reassign a new array to arr2 as follows arr2 = new int [] { 15, 34, 56, 16, 7 };

15 The length property of arrays In Java, every array has a field property called length The length field is automatically assigned a value that is equal to the number of elements in the array For example, the String array cities has 5 elements String[] cities = {“Accra”, “Cape Coast”, “Tamale”, “Ho”, “Kumasi” }; int namesOfCities = cities.length; System.out.println(namesOfCities); Using the length field, the output of the code is 5 Important: Arrays are always of the same size: their lengths cannot be changed once they are created!

16 public class ArrayLengthProperty { public static void main( String[ ] arl ) { String[ ] towns = { "Tema", "Ada", "Aburi", "Kasoa" }; int numOfTowns = towns.length; System.out.println( "There are " + towns.length + " number of towns in the array" ); System.out.println( "The number of towns in the array is " + numOfTowns ); }

17 Array Size and Default Values When an array is created, the array size must be given to specify the number of elements that can be stored in the array The size cannot be changed after the array is created The size can be obtained using arrayName.length When an array is created, its elements are assigned default values depending on the data types Numeric primitive data types are assigned 0 by default Type char types are ‘\u0000’ by default Type boolean are false by default

18 Example String[] firstNames = {“Debie”, “Clara”, “Tony”, “Kwame”, “Nora”, “Mike”}; for(int i = 0; i < firstNames.length; i++) { System.out.println("Hello " + firstNames[i] + "."); } Output: Hello Debbie. Hello Clara. Hello Tony. Hello Kwame. Hello Nora. Hello Mike.

19 Modifying Array Elements Example: firstNames [0] = “Moses” Now the first name in firstNames[] has been changed from “Debbie” to “Moses”. So the expression names[0] now evaluates to “Moses”. Note: The values of compartments can change, but no new compartments may be added.

20 Modifying Array elements After an array has been created, an indexed variable can be used in the same way as a normal variable In the example below we can modify the elements of the array by using arithmetic operators box[2] = box[0] + box[1]; In the above expression the values in box[1] and box[2] are added and placed in box[2] Consider the following code for( int j = 0; j <= myArray.length; j++) myArray[j] = j; In the above code, the loop assigns 0 to myArray[0], 1 to myArray[1] and so on

21 Array of Objects We have dealt with arrays of primitive data types Arrays can also hold elements of any type including objects If we create a class called Student that has two data fields idNum and famName g to specific complex data types

22 The Enhanced for Loop The enhanced for loop enables the programmer to traverse the complete array sequentially without using an index variable Its general syntax is as follows for( elementType : arrayRefVariable ) { // process the array } The following code displays all the elements in someArray for( datatype someValue : someArray ) System.out.println( someValue );

23 public class ArrayForLoopEnhanced { public static void main( String[] arg) { int[] myArray = { 54, 26, 34, 76, 98, 29, 80, 38, 48, 76, 90 }; int total = 0; for( int countElements: myArray ) { total += countElements; System.out.println("\n Total number of my array elements = " + total + " " + countElements); } System.out.println( "\n " ); }

24 Processing Arrays Arrays are best processed with for loops Reasons why for loops are used in processing arrays are – All array elements are of same data type – They are evenly processed in the same manner repeatedly – The size of an array is always known – for loops are best for processing finite number of elements or data

25 Example int[] fibs = new int[10]; fibs[0] = 1; fibs[1] = 1; for(int i = 2; i < fibs.length; i++) { fibs[i] = fibs[i-2] + fibs[i-1]; System.out.print( fibs[ i ] + “ ”); System.out.println( “\n”); } After running this code, the array fibs[] contains the first ten Fibonacci numbers: 1 1 2 3 5 8 13 21 34 55 Note: array indexes can be expressions

26 Copying Arrays In Java, we can use the assignment statement to copy primitive data type variables, but not with arrays Assigning one array variable to another merely copies one reference to another so that both arrays point to the same memory location We could attempt to write array2 = array1; The above statement does not copy the content of the array referenced by array1 to array2 After the statement is executed array1 and array2 reference the same array The array referenced by array2 is no longer referenced, it becomes garbage to be collected by JVM automatically

27 Copying Arrays Before the assignment boxArray2 = boxArray1; Before the assignment statement, boxArray1 and boxArray2 point to separate memory location After the assignment boxArray2 = boxArray1; After the assignment statement the reference of the boxArray1 is passed to boxArray2 boxArray1 boxArray2 boxArray1 boxArray2 Content of boxArray1 Content of boxArray2 Content of boxArray1 Content of boxArray2

28 Copying arrays Use a loop to copy individual array elements Use the static arraycopy method in the System class Use the clone method to copy arrays We can use a loop to copy every elements of one array to the corresponding elements of another array int[] firstArray = { 17, 5, 34, 55, 22}; int[] secondArray = new int[ firstArray.length ]; for( int i = 0; i < firstArray.length; i++ ) secondArray[ i ] = firstArray[ i ];

29 public class CopyArrays { public static void main( String[] arg ) { int[] firstArray = { 17, 5, 34, 55, 22}; int[] secondArray = new int[ firstArray.length ]; int[] thirdArray = new int[ firstArray.length ]; System.out.println( "This is the content of firstArray"); for( int i = 0; i < firstArray.length; i++ ) System.out.println( "\n " + firstArray[ i ]); System.out.println( "\n\nThis is the content of secondArray"); System.out.println( "\n " + "firstArray" + "\t\t" + "secondArray");

30 for( int i = 0; i < firstArray.length; i++ ) { secondArray[ i ] = firstArray[ i ]; System.out.println( "\n " + firstArray[ i ] + "\t\t\t" + secondArray[ i ]); } System.arraycopy( firstArray, 0, thirdArray, 0, firstArray.length ); System.out.println( "\n\nThis is the content of thirdArray"); for( int i = 0; i < thirdArray.length; i++ ) System.out.println( "\n " + thirdArray[ i ] * 2 ); //System.out.println( "\n " + firstArray[ i ] + "\t\t\t" + secondArray[ i ]); System.out.println( "\n\nThis is the end of the display\n"); }

31 Exercise 1 Which of the following sequences of statements does not create a new array? a. int[] arr = new int[4]; b. int[] arr; arr = new int[4]; c. int[] arr = { 1, 2, 3, 4}; d. int[] arr; just declares an array variable

32 Exercise 2 Given this code fragment, int[] data = new int[10]; System.out.println(data[j]); Which of the following is a legal value of j? a. -1 b. 0 c. 3.5 d. 10 // out of range // legal value // out of range

33 Exercise 3 Which set of data would not be suitable for storing in an array? a.the score for each of the four quarters of a Football match b.your name, date of birth, and score on your physics test c.temperature readings taken every hour throughout a day d.your expenses each month for an entire year // these are different types

34 Exercise 4 What is the value of c after the following code segment? int [] a = {1, 2, 3, 4, 5}; int [] b = {11, 12, 13}; int [] c = new int[4]; for (int j = 0; j < 3; j++) { c[j] = a[j] + b[j]; } c = [12, 14, 16]

35 2-Dimensional Arrays The arrays we've used so far can be thought of as a single row of values. A 2-dimensional array can be thought of as a grid (or matrix) of values Each element of the 2-D array is accessed by providing two indeces: a row index and a column index (A 2-D array is actually just an array of arrays) 01 084 197 236 value at row index 2, column index 0 is 3

36 2-D Array Example Example: A landscape grid of a 20 x 55 acre piece of land: We want to store the height of the land at each row and each column of the grid. We declare a 2D array two sets of square brackets: double[][] heights = new double[20][55]; This 2D array has 20 rows and 55 columns To access the acre at row index 11 and column index 23 user: heights[11][23]


Download ppt "Lecture 5 Arrays A way to organize data. What are Arrays? An array is a named list of data values that all have the same type An array is a collection."

Similar presentations


Ads by Google