CITS2005 Lecture7
CITS2005 Lecture7
1 / 29
Contents
2 / 29
How Objects are Stored
3 / 29
How Objects are Stored
BankAccount
account1 BankAccount Object
balance = 1000
ownerName = "Donald Knuth"
BankAccount
account2
BankAccount
account1 BankAccount Object
balance = 1000
ownerName = "Donald Knuth"
BankAccount
account2
6 / 29
Arrays
7 / 29
Indexing Arrays
public class Nums {
public static void main(String[] args) {
int[] nums = new int[4];
nums[0] = 3;
nums[1] = 1;
nums[2] = 4;
nums[3] = 1;
for (int num : nums) // For each element in nums
System.out.println(num);
}
}
3 1 4 1
9 / 29
Arrays and args
10 / 29
Histogram
• Lets try to put together what we have learned into a Histogram program
• Use Scanner to read in numbers from 1 to 10
• Create a frequency histogram of the numbers entered
• An array is used to store the histogram
• Print them to the terminal
• Note that we will need to use a new method of Scanner called hasNextInt()
• We will also see System.out.print() (not println())
11 / 29
Histogram
12 / 29
Arrays and Objects
13 / 29
Arrays and Objects
• int[] a, b;
14 / 29
Arrays and Objects
• int[] a, b;
• a = new int[3];
15 / 29
Arrays and Objects
• int[] a, b;
• a = new int[3];
• b = a;
16 / 29
Arrays and Objects
• int[] a, b;
• a = new int[3];
• b = a;
• System.out.println(b[2]);
17 / 29
Arrays and Objects
• int[] a, b;
• a = new int[3];
• b = a;
• System.out.println(b[2]);
• a[2] = 9;
18 / 29
Arrays and Objects
• int[] a, b;
• a = new int[3];
• b = a;
• System.out.println(b[2]);
• a[2] = 9;
• System.out.println(b[2]);
19 / 29
Mid-lecture break
20 / 29
Multidimensional Arrays
21 / 29
Multidimensional Arrays
22 / 29
Multidimensional Arrays
myArray
null null null null null
23 / 29
Multidimensional Arrays
0 0 0 0
myArray
[0] null [2] null null
24 / 29
Multidimensional Arrays
• Multidimensional arrays are actually arrays of arrays
• int[][] myArray = new int[5][];
• myArray[0] = new int[2];
• myArray[2] = new int[2];
• myArray[0][0] = 1;
• myArray[2][1] = 3;
1 0 0 3
myArray
[0] null [2] null null
25 / 29
Multidimensional Arrays
26 / 29
Array Initialisation
27 / 29
Arrays and for
28 / 29
Arrays and for
29 / 29