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

Similar documents
Lecture 5: Methods CS2301

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

CS-201 Introduction to Programming with Java

Chapter 5 Methods. 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

Lecture 1: Introduction to Java

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

CS110: PROGRAMMING LANGUAGE I

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

Methods. CSE 114, Computer Science 1 Stony Brook University

Chapter 5 Methods / Functions

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

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

Lecture 06: Classes and Objects

AP CS Unit 3: Control Structures Notes

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

Lab 9: Creating a Reusable Class

( &% class MyClass { }

Functions. CS111 Lab Queens College, CUNY Instructor: Kent Chin

Static Methods. Why use methods?

CS-201 Introduction to Programming with Java

Lesson 05 Methods. MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Lecture 08: Static Fields and Methods

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

Lecture 04 FUNCTIONS AND ARRAYS

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

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

Functions. Lecture 6 COP 3014 Spring February 11, 2018

A Foundation for Programming

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

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

Chapter 6 Methods. Dr. Hikmat Jaber

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

CS 106 Introduction to Computer Science I

CT 229 Methods Continued

Tutorials. Inf1-OP. Learning Outcomes for this week. A Foundation for Programming. Conditionals and Loops 1

Unit 7. Functions. Need of User Defined Functions

Methods. Every Java application must have a main method.

Java Identifiers, Data Types & Variables

CS115 Principles of Computer Science

Methods. Contents Anatomy of a Method How to design a Method Static methods Additional Reading. Anatomy of a Method

Condi(onals and Loops

Java+- Language Reference Manual

CS113: Lecture 4. Topics: Functions. Function Activation Records

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

CONDITIONAL EXECUTION

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

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

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)

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

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

Advanced Computer Programming

Methods and Data (Savitch, Chapter 5)

CSE 114 Computer Science I

PROGRAMMING FUNDAMENTALS

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

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

JAVA GUI PROGRAMMING REVISION TOUR III

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

Pace University. Fundamental Concepts of CS121 1

CSCI 135 Exam #1 Fundamentals of Computer Science I Fall 2014

Building Java Programs

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University

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

Chapter 1. Section 1.4 Subprograms or functions. CS 50 - Hathairat Rattanasook

Language Reference Manual

Learning Outcomes for this week. Inf1-OP. A Foundation for Programming. A Foundation for Programming

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

Lecture 10: Interfaces

CS110D: PROGRAMMING LANGUAGE I

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

Notes - Recursion. A geeky definition of recursion is as follows: Recursion see Recursion.

CS171:Introduction to Computer Science II

CT 229 Arrays Continued

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

Lecture 04 FUNCTIONS AND ARRAYS

Comments are almost like C++

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

Overview. Lab 5 Methods and Parameters

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

Introduction to Computer Science Unit 2. Notes

Functions CMPE-013/L. Functions. Functions What is a function? Functions Remember Algebra Class? Gabriel Hugh Elkaim Winter 2014.

Functions. Prof. Indranil Sen Gupta. Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur. Introduction

Chapter 4 Defining Classes I

Computer Programming: C++

1.00 Lecture 6. Java Methods

Administration. Classes. Objects Part II. Agenda. Review: Object References. Object Aliases. CS 99 Summer 2000 Michael Clarkson Lecture 7

Defining Program Syntax. Chapter Two Modern Programming Languages, 2nd ed. 1

University of Palestine. Mid Exam Total Grade: 100

Introduction to Programming (Java) 4/12

Lexical Considerations

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

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

Computer Science 210 Data Structures Siena College Fall Topic Notes: Methods

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

Methods. Bok, Jong Soon

Admin. CS 112 Introduction to Programming. Recap: Exceptions. Summary: for loop. Recap: CaesarFile using Loop. Summary: Flow Control Statements

CS 302: INTRODUCTION TO PROGRAMMING IN JAVA. Chapter 5: Methods. Lecture 10

Methods. Methods. Mysteries Revealed

Lecture 8 Classes and Objects Part 2. MIT AITI June 15th, 2005

Transcription:

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

Agenda What a method is Why we use methods How to declare a method The four parts of a method How to use (invoke) a method The purpose of the main method

The Concept of a Method Methods are a way of organizing a sequence of statements into a named unit. Reusable Parameterizable (can accept inputs) Organize code into smaller units Easier to understand Any complex process that can exist on its own should be a method Better to have more methods, even if they are not reused.

The Concept of a Method Methods can accept inputs (called arguments) They can then perform some operations with the arguments And can output a value (called a return value) that is the result of the computations inputs method outputs

Square Root Method The square root method accepts a single number as an argument and returns the square root of that number. (argument) number Square Root Method number (return value)

Square Root Method (con t) The computation of square roots involves many intermediate steps between input and output. When we use square root, we don t care about these steps or details. All we need is to get the correct output. Hiding the internal workings of a method and providing the correct answer is known as abstraction 4 Square Root +2,-2 Black Box

Declaring Methods A method has 4 parts: the return type, the name, the arguments, and the body: type name arguments body double sqrt(double num) { // a set of operations that compute // the square root of a number The type, name and arguments together is referred to as the signature of the method Methods with same names must have unique signature

Return Type of a Method The return type of a method may be any data type... inputs method int,double, OR string... The return type of a method is a promise for what data type the output will be A method can return different outputs than inputs A method cannot return multiple types, returns one type Methods can also return nothing in which case they are declared void.

Return Statements The return statement is used in a method to output the result of the method computation. It has the form: return expression-value; The type of the expression_value must be the same as the type of the method: double sqrt(double num) { double answer; // Compute the square root of num // and store in answer return answer; What is the return type of this method?

Return Statements A method exits immediately after it executes the return statement double sqrt(double num) { double answer; // Compute the square root of num // and store in answer return answer; answer = 5 + 4; //never executed, illegal

Multiple Returns An example using multiple returns: int absolutevalue (int num) { if (num < 0) return num; else return num;

void Methods A method of type void does not return a value inputs Used often in practice. method Perform some computation that does not produce a value Affect system state, ex: System.out.println() A void method can have a return statement without any specified value. i.e. return; If no return statement is used in a method of type void, it automatically returns at the end

Method Arguments Methods can take input in the form of arguments. Arguments are used as variables inside the method body. Like variables, arguments must have their type specified. Arguments are specified inside the parentheses that follow the name of the method.

Example Method Here is an example of a method that divides two doubles: double divide(double a, double b) { double answer; answer = a / b; return answer; a,b divide answer = a/b

Method Arguments Multiple method arguments are separated by commas: double divide(double a, double b) { double answer; answer = a / b; return answer; Arguments may be of different types (double/int) double divide(int a, int b) When calling method, exact sequence of input types must be applied

The Method Body The body of a method is a block specified by curly brackets i.e {. The body defines the actions of the method. The method arguments can be used anywhere inside of the body. All methods must have curly brackets to specify the body even if the body contains only one statement or no statements. double divide( double a, double b) { double answer; answer = a / b; return answer;

Invoking Methods To call a method, specify the name of the method followed by a list of comma separated arguments in parentheses: divide(10, 2); //Computes 10/2 If the method has no arguments, you still need to follow the method name with empty parentheses: int size() { //Compute and return size size(); //Calls size

Method Variable Scoping For now, methods can only access their own arguments and local variables. A method cannot access arguments/locals from other methods Even if one method calls another Example 18

Recursive Methods A method can also call itself! When a method calls itself, it needs a stopping condition, called the base case Or else it would call itself without end Example Factorial: Factorial of n, denoted n!: n (n 1) (n 2) 0 0! = 1 (base case)

Factorial Implementation int factorial(int n) { if (n==0) return 1; else { return n * factorial (n-1); 20

Static Methods For now, all the methods we write in lab will be static. static double divide(double a, double b) { return a / b; We'll learn what it means for a method to be static in a later lecture

main A Special Method The only method that we have used in lab up until this point is the main method. The main method is where a Java program always starts when you run a class file (entry point) The main method is static and has a strict signature which must be followed: public static void main(string[] args) {...

main Method (con t) class SayHi { public static void main(string[] args) { System.out.println("Hi, " + args[0]); If you were to type java Program arg1 arg2 argn on the command line, anything after the name of the class file is automatically entered into the args array: java SayHi Sonia In this example args[0] will contain the String "Sonia", and the output of the program will be "Hi, Sonia".

Methods Review What are the four parts of a method and what are their functions? 1.Return type data type returned by the method 2. Name name of the method 3. Arguments inputs to the method 4. Body sequence of instructions executed by the method

What is wrong with the following? static double addsometimes(num1, num2){ double sum; if (num1 < num2){ sum = num1 + num2; String completed = completed ; return completed; Types for the arguments num1 and num2 are not specified String completed does not match the correct double return type Method addsometimes does not always return an answer. This will cause an error in Java because we specified that addsometimes would always return a double.

Example class Max { public static void main(string args[]) { if (args.length == 0) return; int max = Integer.parseInt(args[0]); for (int i=1; i < args.length; i++) { if (Integer.parseInt(args[i]) > max) { max = Integer.parseInt(args[i]); System.out.println(max); After compiling, if you type java Max 3 2 9 2 4 the program will print out 9

Important Points Covered. Methods capture a piece of computation we wish to perform repeatedly into a single abstraction Methods in Java have 4 parts: return type, name, arguments, body. The return type and arguments may be either primitive data types (i.e. int) or complex data types (i.e. Objects), which we will cover next lecture main is a special Java method which the java interpreter looks for when you try to run a class file main has a strict signature that must be followed: public static void main(string args[])