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

Similar documents
Opening Problem. Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.

Opening Problem. Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.

Lecture 5: Methods CS2301

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

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

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

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

Chapter 6 Methods. Dr. Hikmat Jaber

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

Methods. CSE 114, Computer Science 1 Stony Brook University

CS1150 Principles of Computer Science Methods

Chapter 5 Methods / Functions

CS115 Principles of Computer Science

To define methods, invoke methods, and pass arguments to a method ( ). To develop reusable code that is modular, easy-toread, easy-to-debug,

Chapter 5 Methods. Modifier returnvaluetype methodname(list of parameters) { // method body; }

CS1150 Principles of Computer Science Methods

Chapter 5 Methods. Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk

CS110: PROGRAMMING LANGUAGE I

CS-201 Introduction to Programming with Java

CS-201 Introduction to Programming with Java

JAVA Programming Concepts

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

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

CS171:Introduction to Computer Science II

Benefits of Methods. Chapter 5 Methods

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

Lecture #6-7 Methods

Top-down programming design

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

CS1150 Principles of Computer Science Methods

Chapter 5 Methods. public class FirstMethod { public static void main(string[] args) { double x= -2.0, y; for (int i = 1; i <= 5; i++ ) { y = f( x );

Announcements. PS 4 is ready, due next Thursday, 9:00pm. Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am

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

Advanced Computer Programming

Computer Programming, I. Laboratory Manual. Experiment #7. Methods

Functions. x y z. f (x, y, z) Take in input arguments (zero or more) Perform some computation - May have side-effects (such as drawing)

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.

A Foundation for Programming

Lecture 1 Java SE Programming

CS313D: ADVANCED PROGRAMMING LANGUAGE. Lecture 3: C# language basics II

COMP-202. Recursion. COMP Recursion, 2011 Jörg Kienzle and others

CS111: PROGRAMMING LANGUAGE II

2/3/2018 CS313D: ADVANCED PROGRAMMING LANGUAGE. Lecture 3: C# language basics II. Lecture Contents. C# basics. Methods Arrays. Dr. Amal Khalifa, Spr17

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

Loops. CSE 114, Computer Science 1 Stony Brook University

Chapter 2. Procedural Programming

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

Encapsulation. You can take one of two views of an object: internal - the structure of its data, the algorithms used by its methods

CS110D: PROGRAMMING LANGUAGE I

Java Methods. Lecture 8 COP 3252 Summer May 23, 2017

CIS 110 Introduction To Computer Programming. February 29, 2012 Midterm

QUIZ 2 Introduction to Computer Science (COMP 250) Mon. March 2, 2009 Professor Michael Langer

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

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Object Oriented Methods : Deeper Look Lecture Three

Practice Questions for Chapter 9

Name: Username: I. 20. Section: II. p p p III. p p p p Total 100. CMSC 202 Section 06 Fall 2015

CS313D: ADVANCED PROGRAMMING LANGUAGE

CS1150 Principles of Computer Science Loops (Part II)

Class, Variable, Constructor, Object, Method Questions

Introduction to programming using Python

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

Arrays. 1 Index mapping

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

Constants. Why Use Constants? main Method Arguments. CS256 Computer Science I Kevin Sahr, PhD. Lecture 25: Miscellaneous

Week 6 CS 302. Jim Williams, PhD

Names, Scopes, and Bindings. CSE 307 Principles of Programming Languages Stony Brook University

INDEX. A SIMPLE JAVA PROGRAM Class Declaration The Main Line. The Line Contains Three Keywords The Output Line

Table of Contents Date(s) Title/Topic Page #s. Chapter 4: Writing Classes 4.1 Objects Revisited

M e t h o d s a n d P a r a m e t e r s

EECS168 Exam 3 Review

Names, Scopes, and Bindings. CSE 307 Principles of Programming Languages Stony Brook University

Activity 6: Loops. Content Learning Objectives. Process Skill Goals

Questions Answer Key Questions Answer Key Questions Answer Key

CS 455 Midterm Exam 1 Spring 2015 [Bono] Thursday, Feb. 19, 2015

CS111: PROGRAMMING LANGUAGE II

Recap: Assignment as an Operator CS 112 Introduction to Programming

Chapter 3 Function Overloading

CONDITIONAL EXECUTION

Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

Anatomy of a Class Encapsulation Anatomy of a Method

Introduction to Programming (Java) 4/12

11/19/2014. Objects. Chapter 4: Writing Classes. Classes. Writing Classes. Java Software Solutions for AP* Computer Science A 2nd Edition

Methods Summer 2010 Margaret Reid-Miller

University of Palestine. Mid Exam Total Grade: 100

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

Questions Answer Key Questions Answer Key Questions Answer Key

C Programming for Engineers Functions

CS 112 Introduction to Programming

Computer Programming, I. Laboratory Manual. Final Exam Solution

Lecture 9 - C Functions

Introduction to Software Development (ISD) Week 3

Chapter 5: Methods. by Tony Gaddis. Starting Out with Java: From Control Structures through Objects. Fourth Edition

C212 Early Evaluation Exam Mon Feb Name: Please provide brief (common sense) justifications with your answers below.

Introduction to Programming Using Java (98-388)

Selected Questions from by Nageshwara Rao

Bjarne Stroustrup. creator of C++

CS 101 Spring 2007 Midterm 2 Name: ID:

Transcription:

Announcements PS 3 is due Thursday, 10/6 Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am Room TBD Scope: Lecture 1 to Lecture 9 (Chapters 1 to 6 of text) You may bring a sheet of paper (A4, both sides) Tutoring schedule is now updated Reading assignment for this lecture: Chapter 6

Methods 2

Opening problem Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. 3

Problem int sum = 0; for (int i = 1; i <= 10; i++) sum = sum + i; System.out.println("Sum from 1 to 10 is " + sum); sum = 0; for (int i = 20; i <= 30; i++) sum = sum + i; System.out.println("Sum from 20 to 30 is " + sum); sum = 0; for (int i = 35; i <= 45; i++) sum = sum + i; System.out.println("Sum from 35 to 45 is " + sum); 4

Problem int sum = 0; for (int i = 1; i <= 10; i++) sum += i; System.out.println("Sum from 1 to 10 is " + sum); sum = 0; for (int i = 20; i <= 30; i++) sum += i; System.out.println("Sum from 20 to 30 is " + sum); sum = 0; for (int i = 35; i <= 45; i++) sum += i; System.out.println("Sum from 35 to 45 is " + sum); 5

Solution public static int sum(int i1, int i2) { int sum = 0; for (int i = i1; i <= i2; i++) sum += i; return sum; public static void main(string[] args) { System.out.println("Sum from 1 to 10 is " + sum(1, 10)); System.out.println("Sum from 20 to 30 is " + sum(20, 30)); System.out.println("Sum from 35 to 45 is " + sum(35, 45)); 6

Defining methods A method is a collection of statements that are grouped together to perform an operation. Define a method Invoke a method { { int z = max(x, y); actual parameters (arguments) After a method is defined, it can be called (invoked). 7

Defining and calling a method method header method body modifier Define a method return value type method name return value formal parameters parameter list method signature Invoke a method int z = max(x, y); actual parameters (arguments) 8

Method signature Method signature is the combination of the method name and the parameter list. method header method body modifier Define a method return value type method name formal parameters parameter list method signature Invoke a method int z = max(x, y); actual parameters (arguments) return value 9

Formal parameters The variables defined in the method header are known as formal parameters. method header method body modifier Define a method return value type method name formal parameters parameter list method signature Invoke a method int z = max(x, y); actual parameters (arguments) return value 10

Actual parameters When a method is invoked, you pass a value to the parameter. This value is referred to as actual parameter or actual argument. method header method body modifier Define a method return value type method name formal parameters parameter list method signature Invoke a method int z = max(x, y); actual parameters (actual arguments) return value 11

Return value type A method may return a value. The returnvaluetype is the data type of the value the method returns. If the method does not return a value, the returnvaluetype is the keyword void. For example, the returnvaluetype in the main method is void. method header method body modifier Define a method return value type method name return value formal parameters parameter list method signature Invoke a method int z = max(x, y); actual parameters (arguments) 12

Calling methods After max is defined as a method, we can call it as in: max(i,j) 13

animation Calling methods pass the value of i pass the value of j public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); 14

animation Trace method invocation i is now 5 public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); 15

animation Trace method invocation j is now 2 public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); 16

animation Trace method invocation invoke max(i, j) public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); 17

animation Trace method invocation invoke max(i, j) Pass the value of i to num1 Pass the value of j to num2 public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); 18

animation Trace method invocation declare variable result public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); 19

animation Trace method invocation (num1 > num2) is true since num1 is 5 and num2 is 2 public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); 20

animation Trace method invocation result is now 5 public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); 21

animation Trace method invocation return result, which is 5 public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); 22

animation Trace method invocation return max(i, j) and assign the return value to k public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); 23

animation Trace method invocation Execute the print statement public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); 24

Caution A return statement is required for a value-returning method. The method shown below in (a) is logically correct, but it has a compilation error because the Java compiler thinks it is possible that this method does not return any value. public static int sign(int n) { if (n > 0) return 1; if (n == 0) return 0; if (n < 0) return 1; (a) Should be public static int sign(int n) { if (n > 0) return 1; if (n == 0) return 0; return 1; (b) To fix this problem, delete if (n < 0) in (a), so that the compiler will see a return statement to be reached regardless of how the if statement is evaluated. 25

Reuse methods from other classes NOTE: One of the benefits of methods is for reuse. Assume that max is defined in the class named TestMax. The max method can be invoked from any class besides TestMax. If you create a new class Test, you can invoke the max method using ClassName.methodName (e.g., TestMax.max) inside Test. 26

Call stacks 27

animation Trace call stack i is declared and initialized public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); i: 5 The main method is invoked. 28

animation Trace call stack j is declared and initialized public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); The main method is invoked. j: 2 i: 5 29

animation Trace call stack Declare k public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); Space required for the main method k: j: 2 i: 5 The main method is invoked. 30

animation Trace call stack Invoke max(i, j) public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); Space required for the main method k: j: 2 i: 5 The main method is invoked. 31

animation Trace call stack pass the values of i and j to num1 and num2 public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); num2: 2 num1: 5 Space required for the main method k: j: 2 i: 5 The max method is invoked. 32

animation Trace call stack Declare result public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); result: num2: 2 num1: 5 Space required for the main method k: j: 2 i: 5 The max method is invoked. 33

animation Trace call stack (num1 > num2) is true public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); result: num2: 2 num1: 5 Space required for the main method k: j: 2 i: 5 The max method is invoked. 34

animation Trace call stack Assign num1 to result public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); Space required for the max method result: 5 num2: 2 num1: 5 Space required for the main method k: j: 2 i: 5 The max method is invoked. 35

animation Trace call stack Return result and assign it to k public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); Space required for the max method result: 5 num2: 2 num1: 5 Space required for the main method k:5 j: 2 i: 5 The max method is invoked. 36

animation Trace call stack Execute print statement public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); Space required for the main method k:5 j: 2 i: 5 The main method is invoked. 37

void method example This type of method does not return a value. The method performs some actions though. 38

Passing parameters public static void nprintln(string message, int n) { for (int i = 0; i < n; i++) { System.out.println(message); Suppose you invoke the method using nprintln( Welcome to Java, 5); What is the output? Suppose you invoke the method using nprintln( Computer Science, 15); What is the output? Can you invoke the method using nprintln(15, Computer Science ); 39

Pass by value (next) This program demonstrates passing values to the methods. public static void main(string[] args) { int i = 3; int j = 4; swap(i, j); System.out.println(i + + j); public static void swap(int x, int y) { int temp = x; x = y; y = temp; 40

Pass by value (cont.) 41

Modularizing code Methods can be used to reduce redundant coding and enable code reuse. Methods can also be used to modularize code and improve the quality of the program. Compare Palindrome.java and Palindrome2.java 42

Overloading methods Same method name with different signatures Example: Overloading the name max with different meaning public static double max(double num1, double num2) { { return num1; { return num2; 43

Ambiguous invocation Sometimes there may be two or more possible matches for an invocation of a method, but the compiler cannot determine the most specific match. This is referred to as ambiguous invocation. Ambiguous invocation is a compile error. 44

Example: Ambiguous invocation public class AmbiguousOverloading { public static void main(string[] args) { System.out.println(max(1, 2)); public static double max(int num1, double num2) { return num1; return num2; public static double max(double num1, int num2) { return num1; return num2; 45

Scope of local variables A local variable: a variable defined inside a method Scope: the part of the program where the variable can be referenced The scope of a local variable starts from its declaration and continues to the end of the block that contains the variable A local variable must be declared before it can be used like any other variable! 46

Scope of local variables (cont.) You can declare a local variable with the same name multiple times in different nonnesting blocks in a method, but you cannot declare a local variable twice in nested blocks. 47

Scope of local variables (cont.) A variable declared in the initial action part of a for loop header has its scope in the entire loop. But a variable declared inside a for loop body has its scope limited in the loop body from its declaration and to the end of the block that contains the variable. The scope of i The scope of j public static void method1() {.. for (int i = 1; i < 10; i++) {.. int j;... 48

Scope of local variables (cont.) It is fine to declare i in two non-nesting blocks public static void method1() { int x = 1; int y = 1; for (int i = 1; i < 10; i++) { x += i; for (int i = 1; i < 10; i++) { y += i; It is wrong to declare i in two nesting blocks public static void method2() { int i = 1; int sum = 0; for (int i = 1; i < 10; i++) sum += i; 49

Scope of local variables (cont.) // Fine with no errors public static void correctmethod() { int x = 1; int y = 1; // i is declared for (int i = 1; i < 10; i++) { x = x + i; // i is declared again for (int i = 1; i < 10; i++) { y = y + i; 50

Scope of local variables (cont.) // With errors public static void incorrectmethod() { int x = 1; int y = 1; for (int i = 1; i < 10; i++) { int x = 0; x = x + i; 51

Method abstraction You can think of the method body as a black box that contains the detailed implementation for the method. Optional arguments for Input Optional return value Method Header Method body Black Box 52

Benefits of methods Write a method once and reuse it anywhere Information hiding. Hide the implementation from the user Reduce complexity 53