Computer Science is... Machine Learning Machine learning is the study of computer algorithms that improve automatically through experience. Example: develop adaptive strategies for the control of epileptic seizures through neurostimulation. (X-ray showing a neurostimulator.)
How many iterations does the following loop consist of? int x = 5; while (x > 4) { System.out.println( I have to write + this over and over. ); x++; }
Infinite Loops: A Common Logical Error An infinite loop executes until the user interrupts (terminates) the program. This is what happens when the statements in the body of a while loop never update the loop condition to false 3
What will be displayed? Why is it the wrong result? Correct the program so that it displays the right sum. public class Sum { public static void main(string[] args) { final int MAX = 5; int sum = 0; int i = 1; while(i < MAX) { sum = sum + i; System.out.println("Sum: " + sum); i = i + 1; System.out.println("i: " + i); System.out.println(); } } } System.out.println("The sum of integers from 1 to " + MAX + " is: " + sum); 4
Sum: 1 i: 2 Sum: 3 i: 3 Sum: 6 i: 4 Sum: 10 i: 5 The sum of the integers from 1 to 5 is: 10
Off-By-One Errors It is a common logical error to write loop conditions that result in the loop body being executed one time too few, or one time too many You should always test your code to check that your loops conditions do not cause such errors 6
Nested Loops Like if and if-else statements, loops can be nested Every time the body of the outer loop is executed, the inner loop will go through its entire set of iterations 7
What does this display? public class NestedLoop { public static void main(string[] args) { final int MAX = 4; int outercount, innercount; } } outercount = 1; while(outercount <= MAX) { innercount = 1; while (innercount <= MAX) { System.out.print("(" + outercount + "," + innercount + ") "); innercount++; } System.out.println(); outercount++; } System.out.println("Done."); 8
(1,1) (1,2) (1,3) (1,4) (2,1) (2,2) (2,3) (2,4) (3,1) (3,2) (3,3) (3,4) (4,1) (4,2) (4,3) (4,4) Done.
What does this display? public class AnotherNestedLoop { public static void main(string[] args) { final int MAX = 4; int outercount, innercount; } } outercount = 1; while(outercount <= MAX) { innercount = 1; while (innercount <= outercount) { System.out.print("(" + outercount + "," + innercount + ") "); innercount++; } System.out.println(); outercount++; } System.out.println("Done."); 10
(1,1) (2,1) (2,2) (3,1) (3,2) (3,3) (4,1) (4,2) (4,3) (4,4) Done.
The for Statement 12
Example: a for loop for(int x = 0; x < 4; x++) { System.out.println( I have to write + this over and over. ); } I have to write this over and over. I have to write this over and over. I have to write this over and over. I have to write this over and over.
for loops are a little different from while loops for (initialization; condition; follow-up action) One statement for (initialization; condition; follow-up action) One block of statements 14
Components of a for loop for(int x = 0; x < 4; x++) { System.out.println( I have to write + this over and over. ); } 15
Logic of a for Statement initialization false condition evaluated true body follow-up (rest of the program) 16
Logic of a for Statement x=0 false x<5 true {loop body} x++ (rest of the program) 17
for Loops as while Loops A for loop is equivalent to the following while loop structure: initialization; while ( condition ) { for-loop body; follow-up; } 18
AnotherCounter.java public class AnotherCounter { public static void main(string[] args) { final int LIMIT = 3; int count = 0; for (count=1; count <= LIMIT; count++) { System.out.println(count); } } } System.out.println("Done. " + count); 19
AnotherCounter.java public class AnotherCounter { public static void main(string[] args) { final int LIMIT = 3; int count = 0; for (count=1; count <= LIMIT; count++) { System.out.println(count); } } } System.out.println("Done. " + count); Console: 1 LIMIT: 3 2 count: 1 2 3 4 3 Done. 4 20
What shape does this display? public class Stars { public static void main (String[] args) { final int MAX_ROWS = 10; } } for (int row = 1; row <= MAX_ROWS; row++) { for (int star = 1; star <= row; star++) { System.out.print("*"); } System.out.println(); }
What Shape does this Display? public class WhatIsThis { public static void main(string[] args) { final int MAX_ROWS = 10; for (int row = 1; row <= MAX_ROWS; row++) { for (int space = 1; space <= MAX_ROWS - row; space++) { System.out.print(" "); } for (int star = 1; star <= row * 2; star++) { System.out.print("*"); } System.out.println(); } for (int base = 3; base > 0; base--) { for (int space = 1; space <= MAX_ROWS-1; space++) { System.out.print(" "); } System.out.println("**"); } } }
Details about the for Statement Each expression in the header of a for loop is optional If the initialization portion is left out, no initialization is performed If the condition portion is left out, it is always considered to evaluate to true, and therefore creates an infinite loop If the increment portion is left out, no increment operation is performed Both semi-colons are always required in the for loop header 23
24
Arrays 25
A variable of type int. int number = 5 In memory: 5
A variable of type int. int number = 5 In memory: 5 An integer array corresponds to variable of type int[]. int[] weights = {5,6,0,4,0,1,2,12,82,1} In memory: 5 6 0 4 0 1 2 12 82 1
An array is a fixed-size, ordered collection of elements of the same type. int[] weights = {5,6,0,4,0,1,2,12,82,1} In memory: 5 6 0 4 0 1 2 12 82 1
Why use arrays? They make large amounts of data easier to handle. int[] weights = {5,6,0,4,0,1,2,12,82,1} In memory: 5 6 0 4 0 1 2 12 82 1
Each cell in the array has an index. e.g. The cell that contains 82 has index 8. The cell that contains 5 has index 0. In memory: 5 6 0 4 0 1 2 12 82 1 0 1 2 3 4 5 6 7 8 9
Each cell in the array has an index. e.g. The cell that contains 82 has index 8. The cell that contains 5 has index 0. In memory: 5 6 0 4 0 1 2 12 82 1 0 1 2 3 4 5 6 7 8 9 So you can write: int j = weights[8] + weights[0];
Array Basics 32
Array Declaration Examples double[] prices; Declares an array called prices Each element in this array is a double; variable prices is of type double[] char[] code; Declares an array called code Each element of this array is a char; variable code is of type char[] String[] names; Declares an array called names Each element of this array is a String; variable names is of type String[] 33
What does this display? public class FirstArray { public static void main(string[] args){ String[] names = {"Jordan", "Jesse", "Joshua"}; for(int i = 1; i >= -1; i = i - 1) System.out.println(names[i+1]); } }
What does this display? public class FirstArray { public static void main(string[] args){ String[] names = {"Jordan", "Jesse", "Joshua"}; for(int i = 1; i >= -1; i = i - 1) System.out.println(names[i]); } }
Review: how primitive types are stored in memory Example: int number = 5 In memory: number 5 number represents a location in memory where the integer 5 is stored
Array types are NOT primitive types Example: int[] weights = {8,6,0,4,0,1,2,12,82,1} weights 101011 8 6 0 4 0 1 2 12 82 1 weights represents a location in memory where the address of the first array cell is stored.
Primitive vs. reference types Primitive types: The variable represents the location in memory at which an actual value, like the integer 175. Reference types: The variable represents the location in memory at which another memory address (or reference ) is stored.
int[] weights = {5,6,0,4,0,1,2,12,82,1} In memory: 5 6 0 4 0 1 2 12 82 1
Initializer Lists int[] numbers = {2, 3, 5}; The above statement does all the following in one step: It declares a variable of type int[] called numbers It creates an array which contains 3 elements It stores the address in memory of the new array in variable numbers It sets the value of first element of the array to 2, the value of the second element of the array to 3, and the value of the last element of the array to be 5 Often, these steps are carried out separately. 40
41
Primitive vs. reference types Primitive types: The variable represents the location in memory at which an actual value, like the integer 175. Reference types: The variable represents the location in memory at which another memory address (or reference ) is stored.
Array types are reference types The declaration int[] numberarray; creates a reference variable, which holds a reference to an int[] No array is created yet, just a reference to an array. 43
Array Allocation (1) final int SIZE = 5; int[] numbers; numbers = new int[2 * SIZE]; numbers - SIZE 5 44
Array Allocation (2) final int SIZE = 5; int[] numbers; numbers = new int[2 * SIZE]; numbers 0 0 0 0 0 0 0 0 0 0 SIZE 5 0 1 2 3 4 5 6 7 8 9 45
Allocating Arrays (1) variablename = new type [ size ]; The variable in which the location in memory of the newly created array will be stored new is a reserved word in Java An expression which specifies the number of elements in the array The type of the elements to be stored in the array 46
Allocating Arrays (3) Once an array has been created, its size cannot be changed As with regular variables, the array declaration and the array allocation operation can be combined: type[] variablename = new type[size]; 47
Initializer Lists int[] numbers = {2, 3, 5}; is equivalent to the following code fragment: int[] numbers = new int[3]; numbers[0] = 2; numbers[1] = 3; numbers[2] = 5; 48
Exercise on reference types: what does this display? public class ArrayCopy { public static void main(string[] args){ int[] numbers = {1, 2, 3}; int[] differentnumbers = new int[3]; differentnumbers = numbers; numbers[1] = 2; differentnumbers[1] = 3; System.out.println(numbers[1]); System.out.println(differentNumbers[1]); } }
Each cell in the array has an index. e.g. The cell that contains 82 has index 8. The cell that contains 5 has index 0. In memory: 5 6 0 4 0 1 2 12 82 1 0 1 2 3 4 5 6 7 8 9 So you can write: int j = weights[8] + weights[0];
Array Access Example numbers[0] = 1; numbers[1] = numbers[0]; numbers[2 * SIZE 1] = 2 * numbers[0] + 1; numbers 1 1 0 0 0 0 0 0 0 3 SIZE 5 0 1 2 3 4 5 6 7 8 9 51
Array Length int[] weights = {5,6,0,4,0,1,2,12,82,1} total = weights.length; We can get the length of any array with [arrayname].length Here, total is assigned the value 10.
Array Length int[] weights = {5,6,0,4,0,1,2,12,82,7} total = weights.length; What is the index of the cell containing 7 in terms of weights.length?
Array Length int[] weights = {5,6,0,4,0,1,2,12,82,7} total = weights.length; What is the index of the cell containing 7 in terms of weights.length? Answer: weights.length - 1
The length of an array is a constant int[] weights = {5,6,0,4,0,1,2,12,82,1} weights.length = 2; // illegal! The length field of an array can be used like any other final variable of type int.
Fill in the method init so that it initializes the array list with a decreasing list of integers starting at start. e.g. If myarray has length 5, a call to init(myarray, 20) will assign the following values to an array: {20, 19, 18, 17, 16}. public static void init(int[] list, int start){ // use a loop to assign a value to each cell }
57
Bounds Checking (2) int[] myarray = new int[5]; myarray[5] = 42; // Array myarray contains 5 elements, so // the valid indices for myarray are 0-4 // inclusive // Therefore, the program crashes When this occurs, the error message will mention that the program threw an ArrayIndexOutOfBoundsException The error message should also mention which line in your program caused the latter to crash 58
Reading Exception Output (1) Exception in thread "main" java.lang. ArrayIndexOutOfBoundsException: 5 ` at IndexOutOfBoundsDemo.main(IndexOutOfBoundsDemo.java:11) Method where the problem occurred File where the problem occurred Line number where the problem occurred Nature of the problem and additional information Index we tried to access and caused the crash 59
Review Exercises Which of the following choices is the correct syntax for quickly declaring/initializing an array of integers to store a particular list of values? (1) int[] a = {17, -3, 42, 5, 9, 28}; (2) int a {17, -3, 42, 5, 9, 28}; (3) int[] a = new int[6] {17, -3, 42, 5, 9, 28}; (4) int[6] a = {17, -3, 42, 5, 9, 28}; (5) int[] a = new {17, -3, 42, 5, 9, 28} [6];
Review Exercises Which of the following choices is the correct syntax for quickly declaring/initializing an array of integers to store a particular list of values? (1) int[] a = {17, -3, 42, 5, 9, 28}; (2) int a {17, -3, 42, 5, 9, 28}; (3) int[] a = new int[6] {17, -3, 42, 5, 9, 28}; (4) int[6] a = {17, -3, 42, 5, 9, 28}; (5) int[] a = new {17, -3, 42, 5, 9, 28} [6];
Review Exercises Which of the following choices is the correct syntax for declaring/initializing an array of integers? (1) []int a = [10]int; (2) int a[10]; (3) int[10] a = new int[10]; (4) int[] a = new int[10]; (5) int a[10] = new int[10];
Review Exercises Which of the following choices is the correct syntax for declaring/initializing an array of integers? (1) []int a = [10]int; (2) int a[10]; (3) int[10] a = new int[10]; (4) int[] a = new int[10]; (5) int a[10] = new int[10];
Review Exercises What values are stored in data after this code executes? int[] data = new int[8]; data[0] = 3; data[7] = -18; data[4] = 5; data[1] = data[0]; int x = data[4]; data[4] = 6; data[x] = data[0] * data[1];
Review Exercises 3 3 0 0 6 9 0-18
Review Exercises What values are stored in list after this code executes? int[] list = {2, 18, 6, -4, 5, 1}; for (int i = 0; i < list.length; i++) { list[i] = list[i] + (list[i] / list[0]); }
Review Exercises 3 24 8-5 6 1
Multidimensional Arrays 68
Review: 1-Dim. Array Allocation int[] numbers = new int[10]; numbers 0 0 0 0 0 0 0 0 0 0 0 1 2 3 4 5 6 7 8 9 69
2D Array Allocations (2) int[][] numbers = new int[3][5]; numbers 0 0 0 0 0 0 0 1 2 3 4 1 0 0 0 0 0 2 0 1 2 3 4 0 0 0 0 0 0 1 2 3 4 70
Two-Dimensional Arrays (2) It may be useful to think of two-dimensional arrays as tables of values with rows and columns The first index specifies a row or column The second index specifies an element within a row or column 71
Exercise Declare and create a 4 by 5 by 6 array of doubles called x
Solution Declare and create a 4 by 5 by 6 array of doubles called x double[][][] x = new double[4][5][6]; 73
2D Array Access Example (3) numbers[1][3] = 7; numbers 0 0 0 0 0 0 0 1 2 3 4 1 0 0 0 7 0 2 0 1 2 3 4 0 0 0 0 5 0 1 2 3 4 74
2D Array Access Example (3) numbers[1][3] = 7; numbers[2][4] = numbers[1][3] - 2; numbers 0 0 0 0 0 0 0 1 2 3 4 1 0 0 0 7 0 2 0 1 2 3 4 0 0 0 0 5 0 1 2 3 4 75
2D Array Access Example (2) Consider the expression numbers[1] This expression refers to the element at position 1 of a two-dimensional array of ints This element is an entire one-dimensional array of ints Its type is int[], and therefore can be used in the same manner as a regular variable of type int[] 76
Example int[][] array = new int[2][2]; int[] x = {1, 2}; array[0] = x; int j = array[0][1]
2D Array and length Fields (2) int size = numbers.length; int rowsize = numbers[0].length; numbers 0 0 0 0 0 0 0 1 2 3 4 1 0 0 0 7 0 2 0 1 2 3 4 size 3 0 0 0 0 5 rowsize 5 0 1 2 3 4 78
Exercise Use length to complete the following nested for loops to fill values with a multiplication table: in other words, values[i][j] should contain the result of i*j. int[][] values = new int[5][10]; for(int i = 0; ; ){ for(int j = 0; ; ){ } }
Solution int[][] values = new int[5][10]; for(int i = 0; i < values.length ; i++ ){ for(int j = 0; j < values[0].length; j++ ){ values[i][j] = i*j; } }
Example from before int[][] array = new int[2][2]; int[] x = {1, 2}; array[0] = x; int j = array[0][0]
Example: this compiles, too int[][] array = new int[2][2]; int[] x = {4, 5, 6}; array[0] = x; int j = array[0][0]
Example: this compiles, too int[][] array = new int[2][2]; int[] x = {7}; array[0] = x; int j = array[0][0]
These variations show us that you can create 2D arrays in which the row arrays have different sizes. These are called jagged arrays. 0 0 1 0 0 0 2 0 1 0 0 0 0 1 2
A few more details about methods 85
public static int countmatches(string s1, String s2) 86
General Method Header Syntax modifiers returntype methodname ( parameterlist ) Where: modifiers public, private, static,... (optional) (there can be more than one) returntype primitive or reference type (mandatory) methodname identifier, as defined previously (mandatory) ( (mandatory) parameterlist defined later (optional) ) (mandatory) 87
Access Modifiers: public/private When a method is private, only the methods declared in the same class can call it; When a method is public, any method declared in any class can call it Access modifiers are mutually exclusive; that is, a method header cannot specify more than one access modifier 88
private vs. public Methods Some of the methods in a class only support other methods in the same class: such methods should always be declared private 89
Other Method Modifiers: static Another important modifier is static For now, all the methods we write will be declared static Therefore, the static modifier MUST be included in the header of each method that we write (at least for now) We will cover non-static methods (also called instance methods) when we cover objects 90
91
Calling Methods (1) A method call has the following syntax: classname. methodname( parameters ) The name of the class in which the method is declared 92
A call to a non-void method is an expression Non-void methods can also be used as an operand in a larger expression Examples: int s = add(a, b); Assigns the value returned by the call to method add() with actual parameters a and b to variable s int s = add(a, b) / add(c, d); Divides the value returned by the call to method add() with actual parameters a and b by the value returned by the call to method add() with actual parameters c and d; assigns the quotient to variable s 93
A call to a void method is a statement In other words, you can think of it as representing an action or a side-effect e.g. print this, read this file You cannot use void methods inside expressions 94
95
Overloading Example Consider the following class definition: public class OverloadingDemo { public static double tryme(int x) { return x + 0.375; } public static double tryme(int x, double y) { return x * y; } public static void main(string[] args) { double result = tryme(25, 4.32); System.out.println(result); } } 96
Method Overloading Method overloading is the process of using the same method name for multiple methods declared in the same class The signature of each overloaded method must be unique The signature of a method consists of: the method's name the number of parameters it accepts the types of the parameters it accepts the order of the parameters' types 97
Method Overloading When a method is called, the compiler must be able to determine which version of the method is being invoked by analyzing the types of the actual parameters 98
More Overloading Examples Many methods defined in the Java Standard Class Library are overloaded e.g The print() and println() methods 99
Reference Types 100
Array types are NOT primitive types Example: int[] weights = {8,6,0,4,0,1,2,12,82,1} weights 101011 8 6 0 4 0 1 2 12 82 1 weights represents a location in memory where the address of the first array cell is stored.
Primitive vs. reference types Primitive types: The variable represents the location in memory at which an actual value, like the integer 175. Reference types: The variable represents the location in memory at which another memory address (or reference ) is stored.
Reference types represent objects. An array is an example of an object. Other examples include Scanner and String. More details on objects in Unit 7.
The concepts explained in the following slides apply to ALL reference types, not just arrays.
Review: variable declarations for reference types e.g. int[] array; or Scanner keyboard; BUT the variables represent memory addresses instead of values. No object is actually created in memory yet, just an address to where such an object would go
Array Allocation (1) final int SIZE = 5; int[] numbers; numbers = new int[2 * SIZE]; numbers - SIZE 5 106
Array Allocation (2) final int SIZE = 5; int[] numbers; numbers = new int[2 * SIZE]; numbers 0 0 0 0 0 0 0 0 0 0 SIZE 5 0 1 2 3 4 5 6 7 8 9 107
Creating Objects (1) In general, we use the new operator to create an object: numbers = new int[10]; 2 exceptions. We create objects without using new : When we use array initializer lists int[] numbers = {1, 2, 3}; When we use string literals: fullname = firstname + Frydrychowicz 108
Primitive Types In Memory int i1, i2 = 8; // Line 1 i1 = 6; // Line 2 i2 = i1; // Line 3 Line 1: i1 i2 8 Line 2: i1 6 i2 8 Line 3: i1 6 i2 6 109
Reference Types in Memory int[] a1, a2 = {2, 3, 5}; // Line 1 a1 = new int[3]; // Line 2 a2 = a1; // Line 3 a1-2 3 5 a2 Line 1: 0 1 2 a1 0 0 0 2 3 5 a2 Line 2: 0 1 2 0 1 2 a1 0 0 0 2 3 5 a2 Line 3: 0 1 2 0 1 2 110
a2 is an alias for a1 (they both point to the same thing) a1 0 0 0 2 3 5 a2 Line 3: 0 1 2 0 1 2
Example from a few lectures ago... public class ArrayCopy { public static void main(string[] args){ int[] numbers = {1, 2, 3}; int[] differentnumbers = new int[3]; differentnumbers = numbers; numbers[1] = 2; differentnumbers[1] = 3; System.out.println(numbers[1]); System.out.println(differentNumbers[1]); } }
Aliasing can only happen with reference types!
Another alias example int[] a1 = {2, 3, 5}; // Line 1 int[] a2 = a1; // Line 2 a1[0] = 7; // Line 3 int v = a2[0]; // Line 4 a1 Line 1: 2 3 5 0 1 2 114
Another alias example int[] a1 = {2, 3, 5}; // Line 1 int[] a2 = a1; // Line 2 a1[0] = 7; // Line 3 int v = a2[0]; // Line 4 a1 Line 1: 2 3 5 0 1 2 a1 Line 2: 2 3 5 a2 0 1 2 115
Another alias example int[] a1 = {2, 3, 5}; // Line 1 int[] a2 = a1; // Line 2 a1[0] = 7; // Line 3 int v = a2[0]; // Line 4 a1 7 3 5 a2 Line 3: 0 1 2 116
Another alias example int[] a1 = {2, 3, 5}; // Line 1 int[] a2 = a1; // Line 2 a1[0] = 7; // Line 3 int v = a2[0]; // Line 4 a1 7 3 5 a2 Line 3: 0 1 2 a1 7 3 5 a2 v 7 0 1 2 117
Comparing objects 118
Comparing Objects Using == int[] a1 = {2, 3, 5}; // Line 1 int[] a2 = a1; // Line 2 boolean b = (a1 == a2); // Line 3 a1 2 3 5 Line 1: 0 1 2 a1 2 3 5 a2 Line 2: 0 1 2 a1 2 3 5 a2 b true Line 3: 0 1 2 119
Comparing Objects Using == int[] a1 = {2, 3, 5}; // Line 1 int[] a2 = {2, 3, 5}; // Line 2 boolean b = (a1 == a2); // Line 3 a1 2 3 5 Line 1: 0 1 2 a1 2 3 5 2 3 5 a2 Line 2: 0 1 2 0 1 2 a1 2 3 5 2 3 5 a2 b false Line 3: 0 1 2 0 1 2 120
More on Comparing Objects To see check whether two objects have the same contents, we need to compare their contents manually For arrays, this can be done using a loop to verify whether all elements are the same For other kinds of objects (like Strings), we can use the equals() method 121
Null references 122
NullPointerDemo.java 1 2 3 4 5 6 7 8 9 10 11 public class NullPointerDemo { public static void main(string[] args) { int[] a = null; } } System.out.println("Attempting to retrieve the " + "element stored at index 0 of an array through a " + "null reference variable..."); System.out.println("The value stored at index 0 of " + "this array is: " + a[0]); 123
Reading Exception Output (2) The program's output: Attempting to retrieve the element stored at index 0 of an array through a null reference variable... Exception in thread "main" java.lang.nullpointerexception at NullPointerDemo.main(NullPointerDemo.java:8) ` Nature of the problem 124
How reference variables behave when passed as parameters to a method 125
Example public static void main(string[] args){ int[] list = {5, 1, 3}; scramble(list); System.out.print(list[2]); } public static void scramble(int[] input) { int temp = input[0]; input[0] = input[input.length 1]; input[input.length - 1] = temp; }
What is the content of a3 after calling method mystery. int[] a3 = {7, 2, 8, 10}; mystery(a3); public static void mystery(int[] a) { for (int i = 0; i < a.length - 1; i++) { if (a[i] < a[i + 1]) { a[i] = a[i + 1]; } } }
7 8 10 10
A few review exercises about loops 129
How does the value of j change during the execution of this loop? int j; for(j = 50; j > 0; j=j-1){ } j = j/2;
Iteration Value of j Statement 0 50 int j = 50 1 25 j = j/2 1 24 j = j -1 2 12 j = j/2.........
Iteration Value of j Statement 0 50 int j = 50 1 25 j = j / 2 1 24 j = j - 1 2 12 j = j / 2 2 11 j = j - 1 3 5 j = j / 2 3 4 j = j - 1 4 2 j = j / 2 4 1 j = j - 1 5 0 j = j / 2 5-1 j = j - 1
What is printed? for(int j = 50; j > -2; j=j-1){ j = j/2; System.out.println(j); } System.out.println(j);
Infinite loop: 25 12 5 2 0 0 0 0 0...