The return Statement

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

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

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

Example: Fibonacci Numbers

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

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

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

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

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

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

Instance Members and Static Members

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

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

Example: Count of Points

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

How to swap values of two variables without tmp? However, this naive algorithm is biased. 1

Chapter 4 Defining Classes I

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.

Exercise: Singleton 1

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

Pace University. Fundamental Concepts of CS121 1

Lecture #6-7 Methods

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

ITI Introduction to Computing II

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

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

ITI Introduction to Computing II

Lecture 3. Lecture

CS110D: PROGRAMMING LANGUAGE I

Methods. CSE 114, Computer Science 1 Stony Brook University

Example: Count of Points

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

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

CS18000: Programming I

CS110: PROGRAMMING LANGUAGE I

Object-Based Programming. Programming with Objects

Methods (Deitel chapter 6)

Methods (Deitel chapter 6)

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

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

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

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

Functions. Systems Programming Concepts

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

JAVA: A Primer. By: Amrita Rajagopal

CS-201 Introduction to Programming with Java

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

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

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

Methods: A Deeper Look

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

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

Object Oriented Programming in C#

Programming Languages and Techniques (CIS120)

Comments are almost like C++

Computer Science II (20073) Week 1: Review and Inheritance

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

CS11 Introduction to C++ Fall Lecture 2

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

Chapter 5 Methods / Functions

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

Anatomy of a Class Encapsulation Anatomy of a Method

Programming Language Pragmatics

COMSC-051 Java Programming Part 1. Part-Time Instructor: Joenil Mistal

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

Object-Oriented Programming Concepts

1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides

Advanced Computer Programming

Creating an object Instance variables

CS11 Intro C++ Spring 2018 Lecture 1

CS1004: Intro to CS in Java, Spring 2005

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

1001ICT Introduction To Programming Lecture Notes

Object-Oriented Programming

CS115 Principles of Computer Science

Example: Monte Carlo Simulation 1

Exercise (Revisited)

Making New instances of Classes

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

CS1150 Principles of Computer Science Methods

Basic Principles of OO. Example: Ice/Water Dispenser. Systems Thinking. Interfaces: Describing Behavior. People's Roles wrt Systems

Answers to review questions from Chapter 2

Object Oriented Methods : Deeper Look Lecture Three

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

Introduction to Programming Using Java (98-388)

Chapter 6 Methods. Dr. Hikmat Jaber

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

ECOM 2324 COMPUTER PROGRAMMING II

Lecture 10 Declarations and Scope

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

Object-Oriented Design Lecture 3 CSU 370 Fall 2007 (Pucella) Friday, Sep 14, 2007

CS 231 Data Structures and Algorithms, Fall 2016

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

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

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

DM550 Introduction to Programming part 2. Jan Baumbach.

Transcription:

The return Statement The return statement is the end point of the method. A callee is a method invoked by a caller. The callee returns to the caller if the callee completes all the statements (w/o a return statement, say main()); reaches a return statement; throws an exception (introduced later). As you can see, the return statement is not necessarily at the bottom of the method. 1 Once one defines the return type (except void), the method should guarantee to return a value or an object of that type. 1 Thanks to a lively discussion on November 22, 2015. Zheng-Liang Lu Java Programming 195 / 242

Bad Exampls 1... 2 static int fun1() { 3 while (true); 4 return 0; //unreachable code 5 } 6 7 static int fun2(int x) { 8 if (x > 0) { 9 return x; 10 } 11 // what if x < 0? 12 } 13... Zheng-Liang Lu Java Programming 196 / 242

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 197 / 242

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 198 / 242

Zheng-Liang Lu Java Programming 199 / 242

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 200 / 242

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? 2 2 Thanks to a lively discussion on January 20, 2017. Zheng-Liang Lu Java Programming 201 / 242

A Math Toolbox: Math Class The Math class provides basic mathematical functions and 2 global constants Math.PI 3 and Math.E 4. 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! 3 The constant π is a mathematical constant, the ratio of a circle s circumference to its diameter, commonly approximated as 3.141593. 4 The constant e is the base of the natural logarithm. It is approximately equal to 2.71828. Zheng-Liang Lu Java Programming 202 / 242

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 203 / 242

Recursion 5 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. 5 Recursion is a commom pattern in nature. Zheng-Liang Lu Java Programming 204 / 242

Try Fractal. Zheng-Liang Lu Java Programming 205 / 242

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 206 / 242

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 } 9... 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 207 / 242

Zheng-Liang Lu Java Programming 208 / 242

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. 6 6 The Church-Turing Thesis proves it if the memory serves. Zheng-Liang Lu Java Programming 209 / 242

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 210 / 242

Memory Layout Zheng-Liang Lu Java Programming 211 / 242

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 F 0 = 0, F 1 = 1, and n 2. Zheng-Liang Lu Java Programming 212 / 242

1... 2 static int fib(int n) { 3 if (n > 1) return fib(n 1) + fib(n 2); 4 else if (n == 1) return 1; 5 else return 0; 6 } 7... 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 213 / 242

Zheng-Liang Lu Java Programming 214 / 242

1... 2 static double fibiter(int n) { 3 int x = 0, y = 1; 4 if (n >= 2) { 5 for (int i = 2; i < n; ++i) { 6 int tmp = x + y; 7 x = y; 8 y = tmp; 9 } 10 return y; 11 } else return (n == 1)? y : x; 12 } 13... 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. 7 7 See http://introcs.cs.princeton.edu/java/23recursion/. Zheng-Liang Lu Java Programming 215 / 242

Divide and Conquer For program development, we use the divide-and-conquer strategy 8 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 8 Aka stepwise refinement. Zheng-Liang Lu Java Programming 216 / 242

Computational Thinking 9 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. 9 You should read this: http://rsta.royalsocietypublishing.org/content/366/1881/3717.full Zheng-Liang Lu Java Programming 217 / 242

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 218 / 242

Example: Abstraction of Computer System Zheng-Liang Lu Java Programming 219 / 242

Example: Methods as Control Abstraction Zheng-Liang Lu Java Programming 220 / 242

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 221 / 242

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 222 / 242

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 223 / 242

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 224 / 242

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 225 / 242

Example: Points in 2D Coordinate 1 class Point { 2 double x, y; // fields: data member 3 } 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 226 / 242

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 227 / 242

Data Members The fields are the states of the object. The field may have an access modifier, say public and private. public: accessible from 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. 10 What private is good for maintainability and modularity. 11 10 Thanks to a lively discussion on January 23, 2017. 11 Read http://stackoverflow.com/questions/9201603/ are-private-members-really-more-secure-in-java. Zheng-Liang Lu Java Programming 228 / 242

Function Members As said, the fields are hidden. So we may need accessors and mutators if necessary. Accessors: return the state of the object Mutators: set the state of the object For example, getx() and gety() are accessors, and setpoint(double, double) is one mutator in the class Point. Zheng-Liang Lu Java Programming 229 / 242

Example: Point (Encapsulated) 1 class Point { 2 private double x; 3 private double y; 4 5 double getx() { return x; } 6 double gety() { return y; } 7 8 void setx(double a) { x = a; } 9 void sety(double a) { y = a; } 10 void setpoint(double a, double b) { 11 x = a; 12 y = b; 13 } 14 } Zheng-Liang Lu Java Programming 230 / 242

Unified Modeling Language 12 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) 12 See http://www.tutorialspoint.com/uml/ and http://www.mitchellsoftwareengineering.com/introtouml.pdf. Zheng-Liang Lu Java Programming 231 / 242

Example: Class Diagram for Point Modifiers can be placed before the fields and the methods: + for public for private Zheng-Liang Lu Java Programming 232 / 242

Constructors A constructor is called by the new operator. A constructor acts like other methods. However, its names should be identical to the name of the class and it has no return type. A class may have several constructors if needed. Constructors can be overloaded. Note that the constructors are used only during the objection creation. Constructors cannot be invoked by any object. If you don t define any explicit constructor, Java assumes a default constructor for your class. Moreover, adding any explicit constructor disables the default constructor. Zheng-Liang Lu Java Programming 233 / 242

Parameterized Constructors You can provide specific information to the parameterized constructor during the object creation. For example, 1 class Point { 2... 3 4 Point() {} // restore a default constructor; 5 6 // parameterized constructor 7 Point(double a, double b) { 8 x = a; 9 y = b; 10 } 11... 12 } Zheng-Liang Lu Java Programming 234 / 242

Self-reference You can refer to any (instance) member of the current object within methods and constructors by using this. The most common reason for using the this keyword is because a field is shadowed by method parameters. You can also use this to call another constructor in the same class by invoking this(). Zheng-Liang Lu Java Programming 235 / 242

Example: Point (Revisited) 1 class Point { 2... 3 Point(int x, int y) { 4 this.x = x; 5 this.y = y; 6 } 7... 8 } Note that the this operator cannot be used in static methods. Zheng-Liang Lu Java Programming 236 / 242

Instance Members and Static Members You may notice that, until now, all members are declared w/o static. It means that each object has its own values with behaviors. The aforesaid members are called instance members. Note that these instance members are available only after the object is created. Zheng-Liang Lu Java Programming 237 / 242

Zheng-Liang Lu Java Programming 238 / 242

Static Members The static members belong to the class 13, and are shared between the instance objects. In other word, there is only one copy of the static members, no matter how many objects of the class are created. They are ready once the class is loaded. They can be invoked directly by the class name without using any instance. For example, Math.random(). 13 Aka class members. Zheng-Liang Lu Java Programming 239 / 242

A static method can access other static members. (Trivial.) However, static methods cannot access to instance members directly. (Why?) For example, 1... 2 double getdistancefrom(point p) { 3 return Math.sqrt(Math.pow(this.x p.x, 2) + Math.pow( this.y p.y, 2)); 4 } 5 6 static double distancebetween(point p1, Point p2) { 7 // You cannot access to x and y directly! 8 return Math.sqrt(Math.pow(p1.x p2.x, 2) + Math.pow(p1. y p2.y, 2)); 9 } 10... Zheng-Liang Lu Java Programming 240 / 242

Example: Count of Points 1 class Point { 2... 3 private static int numofpoint = 0; 4 5 Point() { 6 numofpoint++; 7 } 8 9 Point(int x, int y) { 10 this(); // calling the constructor with no input argument; should be placed in the first line in the constructor 11 this.x = x; 12 this.y = y; 13 } 14... 15 } Zheng-Liang Lu Java Programming 241 / 242

Exercise: Singleton 14 In some situations, you may create the only instance of the class. 1 class Singleton { 2 3 // Will be ready as soon as the class is loaded. 4 private static Singleton instance = new Singleton(); 5 6 // Do now allow to invoke the constructor by other classes. 7 private Singleton() {} 8 9 // Only way to obtain the singleton from the outside world. 10 public static Singleton getsingleton() { 11 return instance; 12 } 13 } 14 See any textbook for design patterns. Zheng-Liang Lu Java Programming 242 / 242