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

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

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

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. Dr. Hikmat Jaber

CS115 Principles of Computer Science

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, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

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

Methods. CSE 114, Computer Science 1 Stony Brook University

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; }

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

Chapter 5 Methods / Functions

CS1150 Principles of Computer Science Methods

JAVA Programming Concepts

CS-201 Introduction to Programming with Java

CS1150 Principles of Computer Science Methods

CS-201 Introduction to Programming with Java

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

CS110: PROGRAMMING LANGUAGE I

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java 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

Benefits of Methods. Chapter 5 Methods

CS171:Introduction to Computer Science II

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

Top-down programming design

Advanced Computer Programming

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 );

CS1150 Principles of Computer Science Methods

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

Introduction to Programming (Java) 4/12

Lecture 1 Java SE Programming

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

Computer Programming: C++

( &% class MyClass { }

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

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

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

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)

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

A Foundation for Programming

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #34. Function with pointer Argument

Loops. CSE 114, Computer Science 1 Stony Brook University

Methods. Eng. Mohammed Abdualal

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

CHAPTER 4 FUNCTIONS. 4.1 Introduction

Object Oriented Methods : Deeper Look Lecture Three

Motivations. Chapter 5: Loops and Iteration. Opening Problem 9/13/18. Introducing while Loops

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

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

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

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

Review Chapter 6 in Bravaco. Short Answers 1. This type of method does not return a value. a. null b. void c. empty d. anonymous

Introduction to programming using Python

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

CS1150 Principles of Computer Science Loops (Part II)

Class, Variable, Constructor, Object, Method Questions

M105: Introduction to Programming with Java Midterm Examination (MTA) Makeup Spring 2013 / 2014

EECS168 Exam 3 Review

Lecture 9 - C Functions

Example. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.

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

Chapter 2. Procedural Programming

1 Lexical Considerations

CS110D: PROGRAMMING LANGUAGE I

Chapter 7 User-Defined Methods. Chapter Objectives

Lexical Considerations

Java Programming. MSc Induction Tutorials Stefan Stafrace PhD Student Department of Computing

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

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

Introduction to Programming Using Java (98-388)

Arrays. 1 Index mapping

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

CS313D: ADVANCED PROGRAMMING LANGUAGE

CONDITIONAL EXECUTION

Passing Array to Methods

Every language has its own scoping rules. For example, what is the scope of variable j in this Java program?

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

Chapter 2. Elementary Programming

Assignment 6. Methods Homework Spring 2017 P Question 1 all

EECS402 Lecture 02. Functions. Function Prototype

Final Exam COMP Fall 2004 Dec 16, 2004

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

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

Example: Monte Carlo Simulation 1

Methods and Functions

Java Coding 3. Over & over again!

Methods CSC 121 Fall 2016 Howard Rosenthal

Anatomy of a Class Encapsulation Anatomy of a Method

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

ECE 122. Engineering Problem Solving with Java

Module 7: Arrays (Single Dimensional)

Chapter 3 Function Overloading

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

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

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

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

Transcription:

Chapter 6 Methods 1

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

A Solution 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); 3

Repeated Code 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

Solution Using Method sum public class summethod { public static void main(string[] args) { int result = sum(1,10); System.out.println("Sum from 1 to 10 is:\t" + result); result = sum(20,30); System.out.println("Sum from 20 to 30 is:\t" + result); result = sum(35,45); System.out.println("Sum from 35 to 45 is:\t" + result); //------------------------------------------------------- public static int sum (int num1, int num2) { int sum = 0; for (int i = num1; i <= num2; i++) sum = sum + i; return sum; 5

What is a Method? Think of a method as a black box that contains the detailed implementation for a specific task. The method may take use inputs (parameters) and may retune an out with a specific type. Optional arguments for Input Optional return value Method Header Method body Black Box 6

Benefits of Methods Write a method once and reuse it anywhere Promotes Information hiding (hide the implementation from the user) Facilitate modularity (break the code into manageable modules) Reduce code complexity (better maintenance) 7

Defining Methods A method has a header and a body. => The header is the method declaration. => The body is a a collection of statements grouped together to perform an operation. method header method body public static int max(int num1, int num2) { 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 public static int max(int num1, int num2) { 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) 9

Formal Parameters The variables defined in the method header are known as formal parameters. method header method body public static int max(int num1, int num2) { modifier Define a method re turn value type method name return value formal parameters pa rameter list method signature Invoke a method int z = max(x, y); actual parameters (arguments) int z = max(21,40); 10

Actual Parameters When a method is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. method header method body public static int max(int num1, int num2) { modifier Define a method re turn value type method name return value formal parameters pa rameter list method signature Invoke a method int z = max(x, y); actual parameters (arguments) int z = max(21,40); 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. method header method body public static int max(int num1, int num2) { modifier Define a method re turn value type method name return value formal parameters pa rameter list method signature Invoke a method int z = max(x, y); actual parameters (arguments) int z = max(21,40); 12

Calling Methods Testing method max This program demonstrates calling method max to return the largest of two int values. 13

animation Calling Methods, cont. 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); public static int max(int num1, int num2 ) { 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); public static int max(int num1, int num2) { 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); public static int max(int num1, int num2) { 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); public static int max(int num1, int num2) { 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); public static int max(int num1, int num2) { 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); public static int max(int num1, int num2) { 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); public static int max(int num1, int num2) { 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); public static int max(int num1, int num2) { 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); public static int max(int num1, int num2) { 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); public static int max(int num1, int num2) { 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); public static int max(int num1, int num2) { 24

Program TestMax //class TestMax public class TestMax { public static void main(string[] args) // main method { int i = 5; int j = 2; int k = max(i, j); System.out.println("The maximum of " + i + " and " + j + " is " + k); //============================================================= public static int max(int num1, int num2) // method max { 25

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. 26

Reuse Methods from Other Classes One of the benefits of methods is for reuse. The max method (being public static method) can be invoked from any other class besides TestMax. If you create a new class Test, you can invoke method max using ClassName.methodName (e.g., TestMax.max). You need to compile both classes to be able call method max from class Test. Remember? Math.pow(a,b); Math.sqrt(x); 27

Another Example // illustration of methods in java import java.util.*; public class TestMethods { public static void main (String[] arge) { int a = 10, b = 20; int addresult = Add(a,b); //call method Add System.out.println("Sum of a and b is " + addresult); String mymessage = "Hello World!"; // call method PrintMessage printmessage(mymessage); // method definition public static int Add(int x, int y) { return (x+y); // method definition public static void printmessage(string message) { for (int i = 1; i <= 5; i++) System.out.println(message); 28

Runtime Stack A runtime stack is a structure used to keep track of active (currently running) methods in the program, and order of method calls. Each active method has "activation record" on the stack. The record is the memory space for all local variables in the method. The top activation record on the stack represents the currently running (active) method in the program. The bottom activation record represents the main method often program. Once a method is no longer active, it is removed from the stack (always the top record is removed). 29

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); public static int max(int num1, int num2) { i: 5 The main method is invoked. 30

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); public static int max(int num1, int num2) { The main method is invoked. j: 2 i: 5 31

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); public static int max(int num1, int num2) { Space required for the main method k: j: 2 i: 5 The main method is invoked. 32

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); public static int max(int num1, int num2) { Space required for the main method k: j: 2 i: 5 The main method is invoked. 33

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); public static int max(int num1, int num2) { 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 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); public static int max(int num1, int num2) { result: 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 (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); public static int max(int num1, int num2) { result: num2: 2 num1: 5 Space required for the main method k: j: 2 i: 5 The max method is invoked. 36

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); public static int max(int num1, int num2) { 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. 37

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); public static int max(int num1, int num2) { 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. 38

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); public static int max(int num1, int num2) { Space required for the main method k:5 j: 2 i: 5 The main method is invoked. 39

animation Trace Call Stack Exit Program 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); public static int max(int num1, int num2) { Stack is empty 40

Call Stacks Space required for the max method num2: 2 num1: 5 Space required for the max method result: 5 num2: 2 num1: 5 Space required for the main method k: j: 2 i: 5 Space required for the main method k: j: 2 i: 5 Space required for the main method k: j: 2 i: 5 Space required for the main method k: 5 j: 2 i: 5 Stack is empty (a) The main method is invoked. (b) The max method is invoked. (c) The max method is being executed. (d) The max method is finished and the return value is sent to k. (e) The main method is finished. 41

void Method This type of method does not return a value. The method performs some actions. public static void Even_Odd(int n) { if ((n % 2) == 0) System.out.println(n + is Even. ); System.out.println(n + is Odd. ); See Listing 6.2, page 209, for example method: public static void printgrade(double score) 42

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? 43

Pass by Value It means that the value of the actual parameter (when a variable) is copied into the formal parameter (local variables inside the method). Whatever changes made to the formal parameter are local to the method and do not affect/change the value of the actual parameter. Classic example: The Swap method. 44

Pass by Value Example public class TestPassByValue { public static void main (String[] arge){ int num1 = 1; int num2 = 2; System.out.println("Before calling Swap: num1 = " + num1 + " num2 = " + num1 + "\n"); swap(num1, num2); System.out.println("After calling Swap: num1 = " + num1 + " num2 = " + num2 + "\n"); public static void swap(int n1, int n2){ // method swap System.out.println("Inside swap, before Swapping : n1 = " + n1 + " n2 = " + n1 + "\n"); int temp = n1; n1 = n2; n2 = temp; System.out.println("Inside swap, after Swapping: n1 = " + n1 + " n2 = " + n2 + "\n"); 45

Pass by Value Runtime Stack The values of num1 and num2 are passed to n1 and n2. Executing swap does not affect num1 and num2. Space required for the swap method temp: n2: 2 n1: 1 Space required for the main method num2: 2 num1: 1 Space required for the main method num2: 2 num1: 1 Space required for the main method num2: 2 num1: 1 Stack is empty The main method is invoked The swap method is invoked The swap method is finished The main method is finished 46

Modularizing Code Modularization is software design concept that calls for writing code in modules. Methods (as modules) 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. Starting page 215, see listings 6.6 (GCD), 6.7 (Prime numbers), and 6.8 (converting decimal to hexadecimal). Each has at least one methods in addition to method main(). 47

Overloading Methods Overloading is making a method to work with different types of parameters. Example: Overloading the max Method public static int max(int num1, int num2) { return num1; return num2; public static double max(double num1, double num2) { return num1; return num2; 48

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 compilation error. 49

Ambiguous Invocation public class AmbiguousOverloading { public static void main(string[] args) { System.out.println(max(1,2)); //Error public static double max (int num1, double num2) { return num1; return num2; public static double max (double num1, int num2) { return num1; return num2; 50

Scope of Local Variables Local variable: a variable defined inside a method. Scope: the part of the program where the variable can be referenced (accessible). The scope of a local variable (also known as life-time) starts from its declaration point and continues to the end of the block that contains the variable. A local variable must be declared before it can be used. Java Rule: You can declare a local variable with the same name multiple time in different non-nesting blocks in a method, but you cannot declare a local variable twice in nested blocks. 51

Scope of Local Variables, cont. The scope of i The scope of j public static void method1() {.. for (int i = 1; i < 10; i++) {... int j;... 52

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 = x + i; for (int i = 1; i < 10; i++) { y = 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 = sum + i; 53

Scope of Local Variables, cont. // Homework: code with errors, can you find them? public static void incorrectmethod() { int x = 1; int y = 1; for (int i = 1; i < 10; i++) { int x = 0; int t = 0; x = x + i; i = i + 10; y = y + 10; t = t + 10; 54

End of Chapter 6 55