Method Invocation. Zheng-Liang Lu Java Programming 189 / 226

Similar documents
The return Statement

Recursion 1. Recursion is the process of defining something in terms of itself.

Example: Fibonacci Numbers

Java Programming. U Hou Lok. Java Aug., Department of Computer Science and Information Engineering, National Taiwan University

Exercise. Write a program which allows the user to enter the math grades one by one (-1 to exit), and outputs a histogram.

1 class Lecture6 { 2 3 "Methods" // keywords: 8 return. Zheng-Liang Lu Java Programming 186 / 244

Cloning Arrays. In practice, one might duplicate an array for some reason. One could attempt to use the assignment statement (=), for example,

Variable Scope. The variable scope is the range of the program where the variable can be referenced.

1 class Lecture6 { 2 3 "Methods" / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 10 / Zheng-Liang Lu Java Programming 185 / 248

1 class Lecture5 { 2 3 "Methods" / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 0 / Zheng-Liang Lu Java Programming 176 / 199

1 class Lecture4 { 2 3 "Loops" / References 8 [1] Ch. 5 in YDL 9 / Zheng-Liang Lu Java Programming 125 / 207

Scope of Variables. In general, it is not a good practice to define many global variables. 1. Use global to declare x as a global variable.

Example. Password generator

Lecture 5: Methods CS2301

Wentworth Institute of Technology COMP1050 Computer Science II Spring 2017 Derbinsky. Recursion. Lecture 13. Recursion

1 >> Lecture 3 2 >> 3 >> -- Functions 4 >> Zheng-Liang Lu 172 / 225

Pace University. Fundamental Concepts of CS121 1

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Methods. CSE 114, Computer Science 1 Stony Brook University

Java Programming 2. Zheng-Liang Lu. Java2 304 Fall Department of Computer Science & Information Engineering National Taiwan University

Lecture #6-7 Methods

Nested Loops. A loop can be nested inside another loop.

CS110D: PROGRAMMING LANGUAGE I

34. Recursion. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

Chapter 6 Methods. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

Java Programming 2. Zheng-Liang Lu. Java2 306 Fall Department of Computer Science & Information Engineering National Taiwan University

INTRODUCTION TO C++ FUNCTIONS. Dept. of Electronic Engineering, NCHU. Original slides are from

Object-Based Programming. Programming with Objects

Notes on Chapter Three

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

Chapter 4 Defining Classes I

CS110: PROGRAMMING LANGUAGE I

Example: Monte Carlo Simulation 1

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

Lecture 3. Lecture

Two Approaches to Algorithms An Example (1) Iteration (2) Recursion

Object Oriented Methods : Deeper Look Lecture Three


Answers to review questions from Chapter 2

Methods: A Deeper Look

1001ICT Introduction To Programming Lecture Notes

Lecture 04 FUNCTIONS AND ARRAYS

Exercise (Revisited)

Chapter 6: Methods. Objectives 9/21/18. Opening Problem. Problem. Problem. Solution. CS1: Java Programming Colorado State University

Methods (Deitel chapter 6)

Methods (Deitel chapter 6)

CS1004: Intro to CS in Java, Spring 2005

Advanced Computer Programming

Functions. Systems Programming Concepts

Classes. Classes. Classes. Class Circle with methods. Class Circle with fields. Classes and Objects in Java. Introduce to classes and objects in Java.

Anatomy of a Class Encapsulation Anatomy of a Method

IT 374 C# and Applications/ IT695 C# Data Structures

More About Objects. Zheng-Liang Lu Java Programming 255 / 282

COP3502 Programming Fundamentals for CIS Majors 1. Instructor: Parisa Rashidi

CSE 8B Programming Assignments Spring Programming: You will have 5 files all should be located in a dir. named PA3:

Objects and Classes: Working with the State and Behavior of Objects

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

Instance Members and Static Members

CS-201 Introduction to Programming with Java

Chapter 2: Java OOP I

C Functions. 5.2 Program Modules in C

Object-Oriented Programming

CS-201 Introduction to Programming with Java

Programming Language Pragmatics

Global Variables. ˆ Unlike local variables, global variables are available to all functions involved.

Chapter 5 Methods. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Lecture 04 FUNCTIONS AND ARRAYS

Faculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions

Lecture 05: Methods. AITI Nigeria Summer 2012 University of Lagos.

Fall Semester (081) Dr. El-Sayed El-Alfy Computer Science Department King Fahd University of Petroleum and Minerals

Variables. location where in memory is the information stored type what sort of information is stored in that memory

Cloning Arrays. In practice, one might duplicate an array for some reason. One could attempt to use the assignment statement (=), for example,

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 4

OVERVIEW. Recursion is an algorithmic technique where a function calls itself directly or indirectly. Why learn recursion?

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

Example: Count of Points

News and information! Review: Java Programs! Feedback after Lecture 2! Dead-lines for the first two lab assignment have been posted.!

ITI Introduction to Computing II

Object-Oriented Programming Concepts

COMP-202: Foundations of Programming. Lecture 13: Recursion Sandeep Manjanna, Summer 2015

CS1150 Principles of Computer Science Methods

Container Vs. Definition Classes. Container Class

1 class Lecture5 { 2 3 "Arrays" 4. Zheng-Liang Lu Java Programming 136 / 174

Chapter 4: Writing Classes

JAVA Programming Concepts

CSE123. Program Design and Modular Programming Functions 1-1

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

Chapter 3 - Functions

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

Exercise: Singleton 1

Chapter 6 Methods. Dr. Hikmat Jaber

Object Oriented Programming with Java

Chapter 5 Methods / Functions

Glossary. For Introduction to Programming Using Python By Y. Daniel Liang

Recursion CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2011

Functions and an Introduction to Recursion Pearson Education, Inc. All rights reserved.

Announcements. PS 3 is due Thursday, 10/6. Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am

public class Foo { private int var; public int Method1() { // var accessible anywhere here } public int MethodN() {

Transcription:

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