Variable Scope The variable scope is the range of the program where the variable can be referenced. Variables can be declared in class level, method level, and loop level. In general, a pair of curly brackets defines a particular scope. Moreover, one can declare variables with the same name in different levels of scopes. Yet, one cannot declare the variables with the same name in the same scope. Zheng-Liang Lu Java Programming 186 / 232
Example 1 public class incrementmain { 2 3 static int i = 1; // Aka class member. 4 5 public static void main(string[] args) { 6 System.out.printf("%d\n", i); // Where is i? 7 int i = 2; 8 i++; 9 System.out.printf("%d\n", i); 10 p(); 11 System.out.printf("%d\n", i); 12 } 13 14 static void p() { 15 i = i + 1; 16 System.out.printf("%d\n", i); 17 } 18 } Zheng-Liang Lu Java Programming 187 / 232
Overloading Methods Overloading methods enables you to define the methods with the same name as long as their signatures are different. Overloading methods can make programs clearer and more readable. Note that overloaded methods must have different parameter lists. You cannot overload methods based on different modifiers or return types. Zheng-Liang Lu Java Programming 188 / 232
Exercise (Revisit) Star printing Write a program which prints a certain number of lines with some symbol determined by the user. The program repeats its procedure until the number of lines is negative. If the user enter -1, use * as the default symbol. Zheng-Liang Lu Java Programming 189 / 232
1... 2 static void print(int x, String marker) { 3 for (int i = 1; i <= x; ++i){ 4 for (int j = 1; j <= i; ++j) 5 System.out.printf("%s", marker); 6 System.out.println(); 7 } 8 } 9 10 static void print(int x) { 11 for (int i = 1; i <= x; ++i){ 12 for (int j = 1; j <= i; ++j) 13 System.out.printf(" "); 14 System.out.println(); 15 } 16 } 17... print()s are overloaded. Zheng-Liang Lu Java Programming 190 / 232
1... 2 public static void main (String[] args) { 3... 4 while (true) { 5 System.out.println("Enter a positive integer? "); 6 n = in.nextint(); 7 if (n < 0) break; 8 System.out.println("Choose a symbol? ( 1 to use the default symbol )"); 9 marker = in.next(); 10 if (marker.equals(" 1")) 11 print(n); 12 else 13 print(n, marker); 14 } 15... 16 } 17... in.next() returns a string from keyboard. Be aware that in.next() skips the blanks in the beginning of line. marker.equals() is one method of String object. Zheng-Liang Lu Java Programming 191 / 232
Math Class The Math class contains the methods needed to perform basic mathematical functions. The Math class is public. All methods of Math class are public and static with two global constants Math.PI 1 and Math.E 2. The Math class provides common methods like: max, min, round, ceil, floor, abs, pow, exp, sqrt, cbrt, log, log10, sin, cos, asin, acos, and random. Full document of Math class can be found here. 1 π is a mathematical constant, the ratio of a circle s circumference to its diameter, commonly approximated as 3.141593. 2 e is the base of the natural logarithm. It is approximately equal to 2.71828. Zheng-Liang Lu Java Programming 192 / 232
Example Password generator Write a program which generates ten characters as a password. There may be lower-case letters, upper-case letters, and digital characters in the character sequence. Recall that a character is encoded using an integer. How to generate these characters randomly? Zheng-Liang Lu Java Programming 193 / 232
1... 2 static char getrandomuppercaseletter() { 3 return (char)(math.random() ( Z A + 1) + A ); 4 } 5 6 static char getrandomlowercaseletter() { 7 return (char)(math.random() ( z a + 1) + a ); 8 } 9 10 static char getrandomdigitalcharacter() { 11 return (char)(math.random() ( 9 0 + 1) + 0 ); 12 } 13... Zheng-Liang Lu Java Programming 194 / 232
1... 2 public static void main (String[] args) { 3 System.out.println("Generating a password..."); 4 // def: 0 > upper case, 1 > lower case, 2 > numbers 5 int type; 6 for (int i = 1; i <= 10; ++i){ 7 type = (int)((math.random() 10) % 3); 8 switch (type) { 9 case 0: 10 System.out.printf("%c", getrandomuppercaseletter()); 11 break; 12 case 1: 13 System.out.printf("%c", getrandomlowercaseletter()); 14 break; 15 case 2: 16 System.out.printf("%c", getrandomdigitalcharacter()); 17 break; 18 } 19 } 20 } 21... Zheng-Liang Lu Java Programming 195 / 232
Abstraction Abstraction is a technique for managing complexity of computer systems. Higher level of abstraction hides the detail at lower levels, and provides the interfaces only. The programmer works with the well-defined interface and can add additional levels of functionality that would otherwise be too complex to handle. For example, no need to know how System.out.println() works. Zheng-Liang Lu Java Programming 196 / 232
Example: Abstraction of Computer System Zheng-Liang Lu Java Programming 197 / 232
Example: Methods as Control Abstraction Zheng-Liang Lu Java Programming 198 / 232
Abstraction (Concluded) Control abstraction is the abstraction of actions while data abstraction is that of data structures. One can view the notion of an object as a way to combine abstractions of data and code. It is so-called encapsulation. Zheng-Liang Lu Java Programming 199 / 232
Divide and Conquer When developing a program, you can use the divide-andconquer strategy, aka stepwise refinement, to decompose the original problem into subproblems. The subproblems can be further decomposed into smaller, more manageable problems. Pros: easier to write, reuse, debug, test, modify, maintain, and better facilitating teamwork For most problems, do not write the entire program at once. Be aware that sitting in front of the computer is the last thing when programming. Zheng-Liang Lu Java Programming 200 / 232
Recursion 3 Recursion is the process of defining something in terms of itself. A method that calls itself is said to be recursive. Recursion is an alternative form of program control. It is essentially repetition without a loop. 3 Recursion is a commom pattern in nature. Zheng-Liang Lu Java Programming 201 / 232
Try Fractal. Zheng-Liang Lu Java Programming 202 / 232
In general, to solve a problem using recursion, you break it into subproblems. Each subproblem is the same as the original problem but smaller in size. You can apply the same approach to each subproblem to solve it recursively. Zheng-Liang Lu Java Programming 203 / 232
Example The factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. 4 For example, 5! = 5 4! = 5 (4 3!) = 5 (4 (3 2!)) = 5 (4 (3 (2 1))) = 5 (4 (3 2)) = 5 (4 6) = 5 24 = 120. Can you find the pattern? 4 Note that 0! = 1. Zheng-Liang Lu Java Programming 204 / 232
Zheng-Liang Lu Java Programming 205 / 232
Write a program which determines the 10th factorials. 1... 2 static int factorial(int n) { 3 if (n!= 0) 4 return n factorial(n 1); 5 else 6 return 1; // base condition 7 } 8... Note that there must be a base condition in recursion. So, can you replace a recursive method by a loop? Zheng-Liang Lu Java Programming 206 / 232
Equivalence: Recursion Replaced by Loops 1... 2 int x = 1; 3 for (int i = 10; i > 0; i = i 1) 4 x = i; 5... One intriguing question is, Can we always turn a recursive method into an iterative one? Yes, theoretically. 5 5 The Church-Turing Thesis proves it if the memory serves. Zheng-Liang Lu Java Programming 207 / 232
In Practice Recursion bears substantial overhead. So, the recursive algorithm may execute a bit more slowly than the iterative equivalent. Besides, a deeply recursive method depletes the call stack, which is limited, and causes a exception fast. 6 The decision whether to use recursion or iteration should be based on the nature of, and your understanding of, the problem you are trying to solve. 6 Stack overflow. Zheng-Liang Lu Java Programming 208 / 232
Zheng-Liang Lu Java Programming 209 / 232
Exercise Fibonacci numbers Write a program which determines the first 10 Fibonacci numbers. A sequence F n of Fibonacci numbers is defined by the recurrence relation F n = F n 1 + F n 2, where F 0 = 0, F 1 = 1, and n 2. The first 10 Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, and 34. Zheng-Liang Lu Java Programming 210 / 232
The recursive implementation of fib is very simple and straightforward. Yet, this algorithm isn t efficient since it requires more time and memory. 7 7 fib is an exponential-time algorithm while factorial is a linear-time algorithm. (Why?) Zheng-Liang Lu Java Programming 211 / 232
1... 2 static int fib(int n) { 3 if (n == 1 n == 0) 4 return (n == 1)? 1 : 0; 5 else 6 return fib(n 1) + fib(n 2); 7 } 8... 1... 2 public static void main(string[] args) { 3 int x = 0, y = 1; 4 int tmp = 0; 5 for (int i = 0; i < 10; ++i){ 6 if (i == 0 i == 1) 7 System.out.printf("%2d: %7d\n", i, ((i == 1)? y : x)); 8 else { 9 tmp = x + y; 10 x = y; 11 y = tmp; 12 System.out.printf("%2d: %7d\n", i, y); 13 } 14 } 15 } 16... Zheng-Liang Lu Java Programming 212 / 232
Problem Set Exercise 5.1 (Greatest common divisor) Write a program which receives two positive integers and returns the greatest common divisor using a recursive approach. Exercise 5.2 (Towers of Hanoi) Write a program which performs the classical problem, Towers of Hanoi, and shows the movements of disks. Zheng-Liang Lu Java Programming 213 / 232
Zheng-Liang Lu Java Programming 214 / 232
1 class Lecture6 { 2 3 "Arrays" 4 5 } 6 7 / References 8 [1] Ch. 6 and 7 in YDL 9 / Zheng-Liang Lu Java Programming 215 / 232
Arrays An array variable can reference a large collection of data of the same type. 1 elementtype[] arrayname; // Java convention 2 elementtype arrayname[]; // C convention elementtype can be any data type. The declaration of an array variable does not allocate any space in memory for the array. It creates only a storage location for the reference to an array. 8 So, you cannot assign elements to an array unless it has already been created. 8 If a variable does not contain a reference to an array, the value of the variable is null. Zheng-Liang Lu Java Programming 216 / 232
1 myarray = new elementtype[size]; Creating An Array All arrays in Java are objects. So, new operator returns the reference after creating an object of array. Note that the reference variable type must match the type of object reference returned by the new operator. size is the number of elements in myarray. The assignment operator (=) assigns the reference of the newly created array 9 to myarray. Note that the size of an array cannot be changed after the array is created. 10 9 Aka the memory address. 10 You can try the ArrayList class. Zheng-Liang Lu Java Programming 217 / 232
Arrays in Memory 1 int[] myarray = new int[3]; All elements of an array are stored contiguously in memory. Arrays in Java are zero-based indexing. (Why?) So, myarray[0], myarray[1], and myarray[2]. Zheng-Liang Lu Java Programming 218 / 232
Array Initializer Arrays can be initialized when they are declared. When an array is created, its elements are assigned the default value: 0 for the numeric primitive data types \u0000 for char types false for boolean types An array initializer is a list of comma-separated expressions surrounded by curly braces. 1... 2 int[] myarray = {value0, value1, value2,..., valuek}; 3... Note that there is no need to use new. Zheng-Liang Lu Java Programming 219 / 232
Processing Arrays When processing array elements, we often use a for loop. Since the size of the array is known, it is natural to use a for loop. myarray.length returns the number of elements in myarray. Zheng-Liang Lu Java Programming 220 / 232
Initializing arrays with input values 1... 2 for (int i = 0; i < myarray.length; ++i) 3 myarray[i] = in.nextdouble(); 4... Initializing arrays with random values 1... 2 for (int i = 0; i < myarray.length; ++i) 3 myarray[i] = Math.random() 100; 4... Zheng-Liang Lu Java Programming 221 / 232
Displaying arrays 1... 2 for (int i = 0; i < myarray.length; ++i) 3 System.out.println(myArray[i] + " "); 4... Summing all elements 1... 2 double sum = 0; 3 for (int i = 0; i < myarray.length; ++i) 4 sum += myarray[i]; 5... Zheng-Liang Lu Java Programming 222 / 232
Finding the extreme values 1... 2 double max = myarray[0]; 3 double min = myarray[0]; 4 for (int i = 1; i < myarray.length; ++i) { 5 if (max < myarray[i]) max = myarray[i]; 6 if (min > myarray[i]) min = myarray[i]; 7 } 8... Zheng-Liang Lu Java Programming 223 / 232
Finding the small index of the extreme elements 1... 2 double max = myarray[0]; 3 double min = myarray[0]; 4 int ind max = 0, ind min = 0; 5 for (int i = 1; i < myarray.length; ++i) { 6 if (max < myarray[i]) { 7 max = myarray[i]; 8 ind max = i; 9 } 10 if (min > myarray[i]) { 11 min = myarray[i]; 12 ind min = i; 13 } 14 } 15... Zheng-Liang Lu Java Programming 224 / 232
Random shuffling 1... 2 for (int i = 0; i < myarray.length; ++i) { 3 int j = (int) (Math.random() myarray.length); 4 // swap 5 double tmp = myarray[i]; 6 myarray[i] = myarray[j]; 7 myarray[j] = tmp; 8 } 9... Shifting elements toward left 1... 2 double tmp = myarray[0]; 3 for (int i = 1; i < myarray.length; ++i) 4 myarray[i 1] = myarray[i]; 5 myarray[myarray.length 1] = tmp; 6... Zheng-Liang Lu Java Programming 225 / 232
Copying Arrays To copy the contents of one array into another, you have to copy the array s individual elements into the other array. In practice, we often need to duplicate an array to another. One could attempt to use the assignment statement (=) as follows: 1... 2 // myarray new and myarray old are arrays. 3 myarary new = myarray old; 4... Zheng-Liang Lu Java Programming 226 / 232
It is impossible make two distinct arrays. Recall that arrays in Java are objects. Array variables contain only the memory addresses. In Line 3, myarray new refers to the same array as myarray old! For another example, Zheng-Liang Lu Java Programming 227 / 232
Use a loop to copy individual elements one by one. 1... 2 int[] srcarray = {2, 1, 3, 5, 10}; 3 int[] dstarray = new int[srcarray.length]; 4 for (int i = 0; i < srcarray.length; ++i) 5 dstarray[i] = srcarray[i]; 6... Use the static arraycopy method in the System class. 1... 2 int[] srcarray = {2, 1, 3, 5, 10}; 3 int[] dstarray = new int[srcarray.length]; 4 System.arraycopy(srcArray, 0, dstarray, 0, srcarray. length); 5... Zheng-Liang Lu Java Programming 228 / 232
for-each Loops 11 A for-each loop is designed to cycle through a collection of objects, such as an array, in strictly sequential fashion, from start to finish. 1... 2 for (type itervar: myarray) { 3 statments; 4 } 5... Note that itervar should match the element type of myarray. 11 Beginning with JDK5. Now we have JDK8. Zheng-Liang Lu Java Programming 229 / 232
Example 1... 2 int[] nums = {1, 2, 3, 4, 5, 6, 7, 8,9, 10}; 3 int sum = 0; 4 for (int i = 0; i < nums.length; ++i) 5 sum += nums[i]; 6... Not only is the syntax streamlined, but it also prevents boundary errors. 1... 2 int[] nums = {1, 2, 3, 4, 5, 6, 7, 8,9, 10}; 3 int sum = 0; 4 for (int x: nums) 5 sum += x; 6... But it is not almighty! Zheng-Liang Lu Java Programming 230 / 232
Exercise Deck of Cards Write a program which picks first four cards at random from a deck of 52 cards. 4 suits: Spades, Hearts, Diamonds, Clubs 13 ranks: 2,..., 10, J, Q, K, A Labeling 52 cards by 0, 1,, 51 by a certain rule Shuffle the numbers Pick up the first 4 cards Zheng-Liang Lu Java Programming 231 / 232
1... 2 int[] deck = new int[52]; // defaults are zeros 3 String[] suits = {"Spade", "Heart", "Diamond", "Club"}; 4 String[] ranks = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"}; 5 6 for (int i = 0; i < deck.length; ++i) deck[i] = i; 7 8 for (int i = 0; i < deck.length; ++i) { 9 int j = (int) (Math.random() deck.length); 10 int tmp = deck[i]; 11 deck[i] = deck[j]; 12 deck[j] = tmp; 13 } 14 15 for (int i = 0; i < 4; ++i) { 16 String suit = suits[deck[i] / 13]; 17 String rank = ranks[deck[i] % 13]; 18 System.out.printf("Card number %3d : %s of % 8s\n", deck[i], rank, suit); 19 } 20... Zheng-Liang Lu Java Programming 232 / 232