Method Invocation Note that the input parameters are sort of variables declared within the method as placeholders. When calling the method, one needs to provide arguments, which must match the parameters in order, number, and compatible type, as defined in the method signature. Zheng-Liang Lu Java Programming 189 / 226
In Java, method invocation uses pass-by-value. When the callee is invoked, the program control is transferred from the caller to the callee. For each invocation of methods, OS creates an frame which stores necessary information, and the frame is pushed in the call stack. The callee transfers the program control back to the caller once the callee finishes its job. Zheng-Liang Lu Java Programming 190 / 226
Zheng-Liang Lu Java Programming 191 / 226
Variable Scope The variable scope is the region where the variable can be referenced in the program. Variables can be declared in class level, method level, and loop level. In general, a balanced curly brackets defines a particular scope. One cannot declare the variables with the same name in the same scope. Zheng-Liang Lu Java Programming 192 / 226
1 public class ScopeDemo { 2 Example 3 static int i = 1; // class level 4 5 public static void main(string[] args) { 6 System.out.printf("%d\n", i); // output 1 7 int i = 2; // method level; local 8 i++; 9 System.out.printf("%d\n", i); // output 3 10 p(); 11 System.out.printf("%d\n", i); // output? 12 } 13 14 static void p() { 15 i = i + 1; 16 System.out.printf("%d\n", i); // output? 17 } 18 } What if p(int i) in Line 14? 1 1 Thanks to a lively discussion on January 20, 2017. Zheng-Liang Lu Java Programming 193 / 226
A Math Toolbox: Math Class The Math class provides basic mathematical functions and 2 global constants Math.PI 2 and Math.E 3. All methods are public and static. For example, max, min, round, ceil, floor, abs, pow, exp, sqrt, cbrt, log, log10, sin, cos, asin, acos, and random. Full document for Math class can be found here. You are expected to read the document! 2 The constant π is a mathematical constant, the ratio of a circle s circumference to its diameter, commonly approximated as 3.141593. 3 The constant e is the base of the natural logarithm. It is approximately equal to 2.71828. Zheng-Liang Lu Java Programming 194 / 226
Method Overloading Methods with the same name can coexist and be identified by the method signatures. 1... 2 static int max(int x, int y) {... } 3 // different numbers of inputs 4 static int max(int x, int y, int z) {... } 5 // different types 6 static double max(double x, double y) {... } 7... Zheng-Liang Lu Java Programming 195 / 226
Recursion 4 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 repetition without any loop. 4 Recursion is a commom pattern in nature. Zheng-Liang Lu Java Programming 196 / 226
Try Fractal. Zheng-Liang Lu Java Programming 197 / 226
Example The factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than and equal to n. Note that 0! = 1. For example, 4! = 4 3 2 1 = 4 3! = 24. Can you find the pattern? n! = n (n 1)! In general, f (n) = n f (n 1). Zheng-Liang Lu Java Programming 198 / 226
Write a program which determines n!. 1... 2 static int factorial(int n) { 3 if (n > 0) 4 return n factorial(n 1); 5 else 6 return 1; // base case 7 } 8... Note that there must be a base case in recursion. Time complexity: O(n) Can you implement the same method by using a loop? Zheng-Liang Lu Java Programming 199 / 226
Zheng-Liang Lu Java Programming 200 / 226
Equivalence: Loop Version 1... 2 int s = 1; 3 for (int i = 2; i <= n; i++) { 4 s = i; 5 } 6... Time complexity: O(n) One intriguing question is, Can we always turn a recursive method into a loop version of that? Yes, theoretically. 5 5 The Church-Turing Thesis proves it if the memory serves. Zheng-Liang Lu Java Programming 201 / 226
Remarks Recursion bears substantial overhead. So the recursive algorithm may execute a bit more slowly than the iterative equivalent. Additionally, a deeply recursive method depletes the call stack, which is limited, and causes stack overflow soon. Zheng-Liang Lu Java Programming 202 / 226
Memory Layout Zheng-Liang Lu Java Programming 203 / 226
Example: Fibonacci Numbers Write a program which determines F n, the (n + 1)-th Fibonacci number. The first 10 Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, and 34. The sequence of Fibonacci numbers can be defined by the recurrence relation F n = F n 1 + F n 2, where n 2 and F 0 = 0, F 1 = 1. Zheng-Liang Lu Java Programming 204 / 226
1... 2 static int fib(int n) { 3 if (n > 1) 4 return fib(n 1) + fib(n 2); 5 else 6 return n == 1? 1 : 0; 7 } 8... This recursive implementation is straightforward. Yet, this algorithm isn t efficient since it requires more time and memory. Time complexity: O(2 n ) (Why?!) Zheng-Liang Lu Java Programming 205 / 226
Zheng-Liang Lu Java Programming 206 / 226
1... 2 static double fibiter(int n) { 3 if (n == 0) return 0; 4 if (n == 1) return 1; 5 6 int x = 0, y = 1; 7 for (int i = 2; i <= n; i++) { 8 int z = x + y; 9 x = y; 10 y = z; 11 } 12 return y; 13 } 14... So it can be done in O(n) time. It implies that the recursive one is not optimal. Could you find a linear recursion for Fibonacci numbers? You may try more examples. 6 6 See http://introcs.cs.princeton.edu/java/23recursion/. Zheng-Liang Lu Java Programming 207 / 226
Divide and Conquer For program development, we use the divide-and-conquer strategy 7 to decompose the original problem into subproblems, which are more manageable. For example, selection sort. Pros: easier to write, reuse, debug, modify, maintain, and also better facilitating teamwork 7 Aka stepwise refinement. Zheng-Liang Lu Java Programming 208 / 226
Computational Thinking 8 To think about computing, we need to be attuned to three fields: science, technology, and society. Computational thinking shares with mathematical thinking: the way to solve problems engineering thinking: the way to design and evaluating a large, complex system scientific thinking: the way to understand computability, intelligence, the mind and human behavior. 8 You should read this: http://rsta.royalsocietypublishing.org/content/366/1881/3717.full Zheng-Liang Lu Java Programming 209 / 226
Computational Thinking Is Everywhere! The essence of computational thinking is abstraction. An algorithm is an abstraction of a step-by-step procedure for taking input and producing some desired output. A programming language is an abstraction of a set of strings each of which when interpreted effects some computation. And more. The abstraction process, which is to decide what details we need to highlight and what details we can ignore, underlies computational thinking. The abstraction process also introduces layers. Well-defined interfaces between layers enable us to build large, complex systems. Zheng-Liang Lu Java Programming 210 / 226
Example: Abstraction of Computer System Zheng-Liang Lu Java Programming 211 / 226
Example: Methods as Control Abstraction Zheng-Liang Lu Java Programming 212 / 226
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. Zheng-Liang Lu Java Programming 213 / 226
1 class Lecture7 { 2 3 // Objects and Classes 4 5 } 6 7 // Key words: 8 class, new, this, static, null, extends, super, abstract, final, interface, implements, protected Zheng-Liang Lu Java Programming 214 / 226
Observations for Real Objects Look around. We can easily find many examples for real-world objects. For example, a person and his/her bottle of water. Real-world objects all have states and behaviors. What possible states can the object be in? What possible behaviors can the object perform on the states? Identifying these states and behaviors for real-world objects is a great way to begin thinking in object-oriented programming. From now, OO is a shorthand for object-oriented. Zheng-Liang Lu Java Programming 215 / 226
Software Objects An object keeps its states in fields and exposes its behaviors through methods. Plus, internal states are hidden and the interactions to the object are only performed through an object s methods. This is so-call encapsulation, which is one of OO features. Note that the other OO features are inheritance and polymorphism, which we will see later. Zheng-Liang Lu Java Programming 216 / 226
Classes We often find many individual objects all of the same kind. For example, each bicycle was built from the same blueprint so that each contains the same components. In OO terms, we say that your bicycle is an instance of the class of objects known as Bicycle. A class is the blueprint to create class instances which are runtime objects. Classes are the building blocks of Java applications. Zheng-Liang Lu Java Programming 217 / 226
Example: Points in 2D Coordinate 1 class Point { 2 // data members: fields or attributes 3 double x, y; 4 } 1 public class PointDemo { 2 public static void main(string[] args) { 3 // now create a new instance of Point 4 Point p1 = new Point(); 5 p1.x = 1; 6 p1.y = 2; 7 System.out.printf("(%d, %d)\n", p1.x, p1.y); 8 9 // create another instance of Point 10 Point p2 = new Point(); 11 p2.x = 3; 12 p2.y = 4; 13 System.out.printf("(%d, %d)\n", p2.x, p2.y); 14 } 15 } Zheng-Liang Lu Java Programming 218 / 226
Class Definition First, give a class name with the first letter capitalized, by convention. The class body, surrounded by balanced braces {}, contains data members (fields) and function members (methods) for objects. Zheng-Liang Lu Java Programming 219 / 226
Data Members The fields are the states of the object. The field may have an access modifier, say public and private. public: accessible by all classes private: accessible only within its own class You can decide if these fields are accessible! In practice, all fields should be declared private. However, this private modifier does not quarantine any security. 9 What private is good for maintainability and modularity. 10 9 Thanks to a lively discussion on January 23, 2017. 10 Read http://stackoverflow.com/questions/9201603/ are-private-members-really-more-secure-in-java. Zheng-Liang Lu Java Programming 220 / 226
Function Members As said, the fields are hidden. So we may need getters and setters if necessary: getters: return the state of the object setter: set the state of the object For example, getx() and gety() are getters while setx() and sety() are setters in the class Point. Zheng-Liang Lu Java Programming 221 / 226
Example: Point (Encapsulated) 1 class Point { 2 // data members: fields or attributes 3 private double x; 4 private double y; 5 6 // function members: methods 7 double getx() { return x; } 8 double gety() { return y; } 9 10 void setx(double new x) { x = new x; } 11 void sety(double new y) { y = new y; } 12 } Zheng-Liang Lu Java Programming 222 / 226
Exercise: Phonebook 1 class Contact { 2 private String name; 3 private String phonenumber; 4 5 double getname() { return name; } 6 double getphonenumber() { return phonenumber; } 7 8 void setname(string new name) { name = new name; } 9 void setphonenumber(string new phnnum) { 10 phonenumber = new phnnum; 11 } 12 } Zheng-Liang Lu Java Programming 223 / 226
1 public class PhonebookDemo { 2 3 public static void main(string[] args) { 4 Contact c1 = new Contact(); 5 c1.setname("arthur"); 6 c1.setphonenumber("09xxnnnnnn"); 7 8 Contact c2 = new Contact(); 9 c1.setname("emma"); 10 c1.setphonenumber("09xxnnnnnn"); 11 12 Contact[] phonebook = {c1, c2}; 13 14 for (Contact c: phonebook) { 15 System.out.printf("%s: %s\n", c.getname, 16 c.getphonenumber); 17 } 18 } 19 20 } Zheng-Liang Lu Java Programming 224 / 226
Unified Modeling Language 11 Unified Modeling Language (UML) is a tool for specifying, visualizing, constructing, and documenting the artifacts of software systems, as well as for business modeling and other non-software systems. Free software: http://staruml.io/ (available for all platforms) 11 See http://www.tutorialspoint.com/uml/ and http://www.mitchellsoftwareengineering.com/introtouml.pdf. Zheng-Liang Lu Java Programming 225 / 226
Example: Class Diagram for Point Modifiers can be placed before the fields and the methods: + for public for private Zheng-Liang Lu Java Programming 226 / 226