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)

Similar documents
A Foundation for Programming

Lecture 5: Methods CS2301

CS110D: PROGRAMMING LANGUAGE I

Inf1-OOP. Functions aka Static Methods. Perdita Stevens, adapting earlier version by Ewan Klein. January 11, School of Informatics

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

Functions / Static Methods. Inf1-OP. What s this static method business? Functions / Static Methods. Haskell function: type declaration

2.1 Functions. f (x, y, z)

CSCI 135 Exam #0 Fundamentals of Computer Science I Fall 2013

Introduction to Programming Using Java (98-388)

CS110: PROGRAMMING LANGUAGE I

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

CS 112 Introduction to Programming

Functions (or Static Methods) (Spring 2012)

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

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

Static methods. Not actually a valid Java static method. Fundamentals of Computer Science Keith Vertanen

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

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

McGill University School of Computer Science COMP-202A Introduction to Computing 1

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

Lecture #6-7 Methods

All classes in a package can be imported by using only one import statement. If the postcondition of a method is not met, blame its implementer

DATA TYPES AND EXPRESSIONS

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

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

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

Inf1-OP. Functions aka Static Methods. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. School of Informatics

2.1 Functions. 2.1 Functions. A Foundation for Programming. Functions (Static Methods) x y. f (x, y, z)

Chapter 3 Function Overloading

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

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

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

AP CS Unit 3: Control Structures Notes

Activity 4: Methods. Content Learning Objectives. Process Skill Goals

CONDITIONAL EXECUTION

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

COS 126 Midterm 1 Written Exam Fall 2011

Loops. CSE 114, Computer Science 1 Stony Brook University

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

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

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

CS171:Introduction to Computer Science II

CS-201 Introduction to Programming with Java

2.1 Functions. x y. f (x, y, z) A Foundation for Programming. Functions (Static Methods)

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

CSCI 135 Exam #0 Fundamentals of Computer Science I Fall 2012

(A) 99 ** (B) 100 (C) 101 (D) 100 initial integers plus any additional integers required during program execution

Introduction to Computer Science Unit 2. Notes

Methods. CSE 114, Computer Science 1 Stony Brook University

Introduction to Computer Science Unit 2. Notes

Chapter 5 Methods / Functions

Programming Language Concepts: Lecture 2

CS1150 Principles of Computer Science Loops (Part II)

CS115 Principles of Computer Science

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

Chapter 6 Methods. Dr. Hikmat Jaber

Object- Oriented Analysis, Design and Programming

COMP-202: Foundations of Programming. Lecture 4: Methods Jackie Cheung, Winter 2016

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

Object Oriented Programming in C#

Condi(onals and Loops

COS 126 Midterm 1 Written Exam Fall 2014!

The life and death of objects, sta2cs. CSCI 136: Fundamentals of Computer Science II Keith Vertanen

Inheritance and Polymorphism

Functions / Static Methods. Why are functions so helpful? Inf1-OP. Find Nearest Neighbour to a Central Point

JAVA Programming Concepts

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

Data Abstraction and Specification of ADTs

Total Score /15 /20 /30 /10 /5 /20 Grader

COMP 110/L Lecture 6. Kyle Dewey

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

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

(A) 99 (B) 100 (C) 101 (D) 100 initial integers plus any additional integers required during program execution

Pull Lecture Materials and Open PollEv. Poll Everywhere: pollev.com/comp110. Lecture 12. else-if and while loops. Once in a while

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

CSC207H: Software Design. Java + OOP. CSC207 Winter 2018

We have written lots of code so far It has all been inside of the main() method What about a big program? The main() method is going to get really

Tools : The Java Compiler. The Java Interpreter. The Java Debugger

Java Fundamentals (II)

Lecture Set 4: More About Methods and More About Operators

CSCI 135 Midterm Fundamentals of Computer Science I Fall 2011

CS321 Languages and Compiler Design I. Winter 2012 Lecture 2

Object Oriented Methods : Deeper Look Lecture Three

EECS1710. Announcements. Labtests have been returned Term Test #01 marking is in progress. Next Labtest: Thu Oct 23/Fri Oct 24

Lec 3. Compilers, Debugging, Hello World, and Variables

Total Score /15 /20 /30 /10 /5 /20 Grader

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

CSCI 135 Exam #2 Fundamentals of Computer Science I Fall 2013

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

CLASSES AND OBJECTS. Fundamentals of Computer Science I

Zheng-Liang Lu Java Programming 45 / 79

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

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

Methods. Bok, Jong Soon

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition

COS 126 General Computer Science Fall Written Exam 1

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

Lecture 10 Declarations and Scope

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

Transcription:

2.1 Functions

Functions Take in input arguments (zero or more) Perform some computation - May have side-effects (such as drawing) Return one output value Input Arguments x y z f Return Value f (x, y, z)

Functions (Static Methods) Applications: - Use mathematical functions to calculate formulas - Use functions to build modular programs Examples: - Built-in functions: Math.random(), Math.abs(), Integer.parseInt() These methods return, respectively, a double, double, and int value. - I/O libraries: PennDraw.circle(x,y,halfRadius), PennDraw.line(x0,y0,x1,y1) - User-defined functions: main() 4

Why do we need functions? Break code down into logical sub-steps Readability of the code improves Testability - focus on getting each individual function correct 5

Method Signatures We need some way to uniquely identify a method The name of the method alone isn t enough - PennDraw.square(0.5, 0.5, 0.25) - PennDraw.square(0.5, 0.5, 0.25, 45) The methods have the same name, but do different things! 6

In Class Poll Which of these sets of elements are part of the method signature? 1) Method name, return type, name of parameters 2) Method name, return type, type of parameters 3) Method name, number of parameters 4) Method name, type of parameters 7

Anatomy of a Java Function Java functions It is easy to write your own - Example: double sqrt(double c) input sqrt(c) = c output 2.0 1.414213 return type method name arguments public static double sqrt(double c) {... method signature (excludes return type) Please note that the method signature is defined incorrectly in the figure on pg 188 of your textbook 8

Anatomy of a Java Function Java functions It is easy to write your own - Example: double sqrt(double c) input sqrt(c) = c output 2.0 1.414213 public static double sqrt(double c) 9

Flow of Control Functions provide a new way to control the flow of execution implicit return statement at end of void function 10

Flow of Control What happens when a function is called: - Control transfers to the function - Argument variables are assigned the values given in the call - Function code is executed - Return value is substituted in place of the function call in the calling code - Control transfers back to the calling code Note: This is known as "pass by value" 11

Example Function to reverse a word Apply this word reversal function to reverse a sentence that is entered via command line arguments. Live coding time.. 12

Organizing Your Program Functions help you organize your program by breaking it down into a series of steps - Each function represents some abstract step or calculation - Arguments let you make the function have different behaviors Key Idea: write something ONCE as a function then reuse it many times 13

Scope Scope: the code that can refer to a particular variable - A variable's scope is the entire code block (any any nested blocks) after its declaration Simple example: int count = 1; for (int i = 0; i < 10; i++) { count *= 2; // using 'i' here generates // a compiler error Best practice: declare variables to limit their scope 15

Function Challenge 1 Q. What happens when you compile and run the following code? public class Cubes1 { public static int cube(int i) { int j = i * i * i; return j; public static void main(string[] args) { int N = Integer.parseInt(args[0]); for (int i = 1; i <= N; i++) System.out.println(i + " " + cube(i)); 16

Scope with Functions 17

Tracing Functions public class Cubes1 { public static int cube(int i) { int j = i * i * i; return j; public static void main(string[] args) { int N = Integer.parseInt(args[0]); for (int i = 1; i <= N; i++) System.out.println(i + " " + cube(i)); % javac Cubes1.java % java Cubes1 6 1 1 2 8 3 27 4 64 5 125 6 216 18

Last In First Out (LIFO) Stack of Plates

Method Overloading 20 Two or more methods in the same class may also have the same name This is called method overloading

Method Signature 21 A method is uniquely identified by - its name and - its parameter list (parameter types and their order) This is known as its signature Examples: static int min(int a, int b) static double min(double a, double b) static float min(float a, float b)

22 Return Type is Not Enough Suppose we attempt to create an overloaded circle(double x, double y, double r) method by using different return types: static void circle(double x, double y, double r) {... //returns true if circle is entirely onscreen, false otherwise static boolean circle(double x, double y, double r) {... This is NOT valid method overloading because the code that calls the function can ignore the return value circle(50, 50, 10); - The compiler can t tell which circle() method to invoke - Just because a method returns a value doesn t mean the calling code has to use it

23 Too Much of a Good Thing Automatic type promotion and overloading can sometimes interact in ways that confuse the compiler For example: // version 1 static void printaverage(int a, double b) {... // version 2 static void printaverage(double a, int b) {... Why might this be problematic?

24 Too Much of a Good Thing static void average(int a, double b) { /*code*/ static void average(double a, int b) { /*code*/ Consider if we do this public static void main (String[] args) {... average(4, 8);... The Java compiler can t decide whether to: - promote 7 to 7.0 and invoke the first version of average(), or - promote 5 to 5.0 and invoke the second version Take-home lesson: don t be too clever with method overloading

Function Examples overloading multiple arguments 30

Function Challenge 2 Q. What happens when you compile and run the following code? public class Cubes2 { public static int cube(int i) { int i = i * i * i; return i; public static void main(string[] args) { int N = Integer.parseInt(args[0]); for (int i = 1; i <= N; i++) System.out.println(i + " " + cube(i)); 31

Function Challenge 3 Q. What happens when you compile and run the following code? public class Cubes3 { public static int cube(int i) { i = i * i * i; public static void main(string[] args) { int N = Integer.parseInt(args[0]); for (int i = 1; i <= N; i++) System.out.println(i + " " + cube(i)); 32

Function Challenge 4 Q. What happens when you compile and run the following code? public class Cubes4 { public static int cube(int i) { i = i * i * i; return i; public static void main(string[] args) { int N = Integer.parseInt(args[0]); for (int i = 1; i <= N; i++) System.out.println(i + " " + cube(i)); 33

Function Challenge 5 Q. What happens when you compile and run the following code? public class Cubes5 { public static int cube(int i) { return i * i * i; public static void main(string[] args) { int N = Integer.parseInt(args[0]); for (int i = 1; i <= N; i++) System.out.println(i + " " + cube(i)); 34