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

Similar documents
COMP-202: Foundations of Programming. Lecture 7: Strings and Methods Jackie Cheung, Winter 2015

COMP-202: Foundations of Programming. Lecture 5: Arrays, Reference Type, and Methods Sandeep Manjanna, Summer 2015

COMP-202: Foundations of Programming

COMP-202: Foundations of Programming. Lecture 2: Java basics and our first Java program! Jackie Cheung, Winter 2016

COMP-202: Foundations of Programming. Lecture 2: Java basics and our first Java program! Jackie Cheung, Winter 2015

Warm up Exercise. What are the types and values of the following expressions: * (3 + 1) 3 / / 2.0 (int)1.0 / 2

Introduction to Computer Science Unit 2. Notes

Key Concept: all programs can be broken down to a combination of one of the six instructions Assignment Statements can create variables to represent

COMP-202: Foundations of Programming. Lecture 26: Review; Wrap-Up Jackie Cheung, Winter 2016

A Foundation for Programming

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

COMP-202: Foundations of Programming. Lecture 5: More About Methods and Data Types Jackie Cheung, Winter 2016

CS 106 Introduction to Computer Science I

Lecture 5: Methods CS2301

Algorithms and Programming I. Lecture#12 Spring 2015

Chapter 5 Methods / Functions

Java Programming Fundamentals - Day Instructor: Jason Yoon Website:

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University

COMP-202: Foundations of Programming. Lecture 6: Conditionals Jackie Cheung, Winter 2016

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)

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

AP CS Unit 3: Control Structures Notes

CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics. COMP-202 Unit 1: Introduction

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

First Programs. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

CONDITIONAL EXECUTION

University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner

First Programs. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

Computer Programming, I. Laboratory Manual. Final Exam Solution

CS110: PROGRAMMING LANGUAGE I

APCS Semester #1 Final Exam Practice Problems

CS 231 Data Structures and Algorithms, Fall 2016

COMP-202: Foundations of Programming. Lecture 8: for Loops, Nested Loops and Arrays Jackie Cheung, Winter 2016

Software and Programming 1

1.1 Your First Program

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

A Balanced Introduction to Computer Science, 3/E

Important Java terminology

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

CLASSES AND OBJECTS. Fundamentals of Computer Science I

Welcome to the Primitives and Expressions Lab!

A Balanced Introduction to Computer Science, 3/E David Reed, Creighton University 2011 Pearson Prentice Hall ISBN

CS 11 java track: lecture 1

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

A foundation for programming. Classes and objects. Overview. Java primitive types. Primitive types Creating your own data types

First Programs. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

COMP 250 Winter 2011 Reading: Java background January 5, 2011

COMP-202: Foundations of Programming. Lecture 26: Image Manipulation; Wrap-Up Jackie Cheung, Winter 2015

1.1 Your First Program

Conditionals, Loops, and Style

Lecture 6: While Loops and the Math Class

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 2: SEP. 8TH INSTRUCTOR: JIAYIN WANG

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

PROGRAMMING STYLE. Fundamentals of Computer Science I

! Widely available. ! Widely used. ! Variety of automatic checks for mistakes in programs. ! Embraces full set of modern abstractions. Caveat.

Introduction to Computer Science Unit 2. Notes

Lec 7. for loops and methods

Introduction to Python. Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas

4 Programming Fundamentals. Introduction to Programming 1 1

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

Using APIs. Chapter 3. Outline Fields Overall Layout. Java By Abstraction Chapter 3. Field Summary static double PI

Lecture 12 Modular Programming with Functions

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

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

Java Tutorial. Saarland University. Ashkan Taslimi. Tutorial 3 September 6, 2011

CLASSES AND OBJECTS. Fundamentals of Computer Science I

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8

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

Advanced Object Concepts

Software and Programming 1

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

CS11 Java. Fall Lecture 1

Array. Array Declaration:

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

Introduction to Python. Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas

Conditionals, Loops, and Style. Control flow thus far. if statement. Control flow. Common branching statement Evaluate a boolean expression

CS115 Principles of Computer Science

Using API in Java. EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG

Computer Science II Lecture 1 Introduction and Background

STATIC, ABSTRACT, AND INTERFACE

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

Chapter 6 Methods. Dr. Hikmat Jaber

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

COMP-202: Foundations of Programming. Lecture 14: static, private, public Jackie Cheung, Winter 2015

Primitive Data, Variables, and Expressions; Simple Conditional Execution

COMP 110/L Lecture 5. Kyle Dewey

1.1 Your First Program

CIS 110: Introduction to Computer Programming

Research Group. 2: More types, Methods, Conditionals

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

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

CS 231 Data Structures and Algorithms Fall Event Based Programming Lecture 06 - September 17, Prof. Zadia Codabux

Java Bytecode (binary file)

CS1150 Principles of Computer Science Loops (Part II)

Warm-up: What type of variable should we create to store the following information:

COMP-202: Foundations of Programming. Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015

Lecture 2: Intro to Java

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015

CS 152: Data Structures with Java Hello World with the IntelliJ IDE

Transcription:

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

Announcements Quiz 1 postponed: Due Jan 26 at 11:59pm Assignment 1 postponed: Due on Feb 1 at 11:59pm 2

Review What is the difference between an int and a double? What is the difference between byte, shorts, ints, and longs? What is the different between a char and a String? 3

This Lecture Methods Methods we ve seen so far Using existing Python methods (e.g., String, Math) Defining our own methods 4

Methods We ve been calling certain segments of code methods. public class HelloWorld { } public static void main(string[] args) { } System.out.println("Hello, World!"); 5

Calling Methods We call a method in order to execute the code contained in the method definition. Some examples? Every time you run a program, you are calling the main method of some class of the program. System.out.println(<expr>) is a method call! Math.ceil(<num>) is a method call! Math.log(<num>) is a method call! 6

Purposes of Methods Some methods map an input value to an output value. e.g., Math.ceil(double a) implements f(x) = x. Others simply perform some useful action. e.g., System.out.println()prints a new line. Still others do both of the above (return a value AND perform other actions). 7

Using Java Libraries The JDK comes with many libraries, which contain classes and methods for you to use. String library Math library Swing library (used for graphics) Libraries for networking 8

Math Library Contains useful and common methods you can use off-the-shelf (i.e., don't have to write yourself) Also, constants like E or PI How do you access them? 9

Documentation Read the Application Programming Interface (API) for the specification of a library. e.g., Math library: http://docs.oracle.com/javase/7/docs/api/java/lang /Math.html What information do you get from an API? 10

Sample Entry static double abs(double a) Returns the absolute value of a double value. Name of the method 11

Sample Entry static double abs(double a) Returns the absolute value of a double value. The number and type of input arguments The name of the method together with the number and type of input arguments is called the signature of the method. 12

Sample Entry static double abs(double a) Returns the absolute value of a double value. Description of what the method does. 13

Sample Entry static double abs(double a) Returns the absolute value of a double value. The return type of the method 14

Sample Entry static double abs(double a) Returns the absolute value of a double value. This keyword means this method does not have to be called on a particular object. Don't worry too much about it for now. 15

Sample Entry static double abs(double a) Returns the absolute value of a double value. Based on this API entry, we know that we call use this method with something like: Math.abs(-4.0) and that this expression evaluates into the value 4.0 with type double. 16

Sample Entry static double abs(double a) Returns the absolute value of a double value. We also know that Math.abs("5.0") would result in an error. 17

Questions Give the input arguments (with types), and return types of the following Math library methods, and describe what they do. Math.pow Math.random Math.max 18

void Methods The return type can be void; i.e., these methods do not return a value. The purpose is to have side effects, not to compute a value directly. Note irony of term side effects are intentional! e.g., System.out.println() 19

Question Why doesn t this make sense? String a = System.out.println("hi"); 20

Writing Your Own Methods You can define your own methods! Motivation: Suppose I want to compute the log2 function from last class, at multiple points in my program. I don't want to copy and paste the code into each point where I need it! Instead, I write the method once, which I call log2ceil(double x), and call it whenever I need to. 21

Adding to Our Toolbox Analogy: writing a new method is like adding to our toolbox for something we do often. 22

How To Write A Method public static double log2ceil(double x) { // compute f(x) = ceil(log2(x)) double result = Math.log(x) / Math.log(2.0); return Math.ceil(result); } Keywords, return type of double Method signature, just like in the API Curly braces to define method body 23

General Form Parts: 1. Keywords (e.g., public static) 2. Return type (e.g., void, int, double) 3. Name of method (e.g., log2ceil) 4. Parentheses containing arguments with types (e.g., double) 5. Body of the method (what it actually does) Include return statement if return type is not void 24

Methods That Return Values What would the method definition look like for a method that computes the area of a circle? public static double computeareacircle(double r) What would the method definition look like for a method that compares two Strings and checks if one is the reverse of another? public static boolean checkifreversed(string s1, String s2) 25

Using Methods That Return Values Since these methods return values (and may also have side effects), we can use the result as part of expressions. // sum areas of two circles double sumarea = computeareacircle(5.0) + computeareacircle(4.0); 26

How To Return Values return <expression>; e.g., A pretty useless method: public static int identity(int a) { } return a; // just return a itself The expression returned must match what is expected in the header of the method. Execution returns immediately to where the method was called. 27

return Statement public static double foo(double a) { return a * 2; return a * 3; } Second return statement is unreachable. 28

Printing vs. Returning Be careful of the difference: Write a method that prints the sum of three doubles Write a method that returns the sum of three doubles What would be the return type of the two methods? 29

Tracing the Code Let s use our newly defined method multiple times, and trace the execution of the code! 30

Trace this Code public class TraceLog2 { public static void main(string[] args) { System.out.println(log2ceil(3.0)); System.out.println(log2ceil(6.0)); System.out.println(log2ceil(9.0)); } } public static double log2ceil(double x) { // compute f(x) = ceil(log2(x)) double result = Math.log(x) / Math.log(2.0); return Math.ceil(result); } 31

Example: computeareacircle Fill in the method body of computeareacircle Let's do this together. 32

Exercise Write a method called saygreeting(): it takes two Strings as input, the first represents the speaker, the second represents the listener, it prints a String saying the speaker saying something to the listener, like "<Speaker> says hello to <Listener>" 33

Methods Calling Methods Methods can call other methods. e.g., Let s implement a method that returns the volume of a sphere given its radius, and implement our own cube method! 34

Exercise: Die Roll Write a method that returns a double, which is one of 1.0, 2.0, 3.0, 4.0, 5.0, or 6.0, each selected with equal probability. This corresponds to rolling a six-sided die. What is the return type? What is the list of arguments? Test your method by calling it in the main method. Use methods in the Math library to help you. 35