Introduction to Methods. Previously discussed There are similarities in make up of that can help you remember the construct of a class a class in the.

Slides:



Advertisements
Similar presentations
Parameter passing mechanism: pass-by-reference. The Pass-by-reference mechanism - the agreement Recall: Parameter passing mechanism = agreement between.
Advertisements

Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Numeric literals and named constants. Numeric literals Numeric literal: Example: A numeric literal is a constant value that appears in a Java program.
Chapter 6: User-Defined Functions I
1 Chapter 7 User-Defined Methods Java Programming from Thomson Course Tech, adopted by kcluk.
1 Modularity In “C”. 2 What is Modularity?  Modularity, is the heart of the high level, structured languages.  Means breaking down a big problem into.
CS 201 Functions Debzani Deb.
Chapter 6: User-Defined Functions I
Defining Classes and Methods Chapter 4.1. Key Features of Objects An object has identity (it acts as a single whole). An object has state (it has various.
Nested conditional statements. Previously discussed Conditional statements discussed so far: Syntax of the if-statement: if-statement if-else-statement.
11 Chapter 5 METHODS. 22 INTRODUCTION TO METHODS A method is a named block of statements that performs a specific task. Other languages use the terms.
Introduction to Methods
The switch statement: an N-way selection statement.
Writing algorithms using the while-statement. Previously discussed Syntax of while-statement:
Writing algorithms using the for-statement. Programming example 1: find all divisors of a number We have seen a program using a while-statement to solve.
Programming a computer. What does programming a computer mean ? Programming a computer: Since a computer can only execute machine instructions (encoded.
The break and continue statements. Introduction There are 2 special statements that can affect the execution of loop statements (such as a while-statement)
COMP More About Classes Yi Hong May 22, 2015.
Shorthand operators.
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
Memory organization - storing variables efficiently in the RAM memory.
Lecture # 5 Methods and Classes. What is a Method 2 A method is a set of code which is referred to by name and can be called (invoked) at any point in.
The string data type String. String (in general) A string is a sequence of characters enclosed between the double quotes "..." Example: Each character.
The Rectangle Method. Introduction Definite integral (High School material): A definite integral a ∫ b f(x) dx is the integral of a function f(x) with.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
Chapter 6: User-Defined Functions
Parameter passing mechanism: pass-by-value. Introduction In the last webpage, we discussed how to pass information to a method I have kept it (deliberately)
The dangling-else ambiguity. Previously discussed The Java compiler (translator) consider white space characters (i.e., SPACE, TAB and New line) as insignificant.
The basics of the array data structure. Storing information Computer programs (and humans) cannot operate without information. Example: The array data.
 2005 Pearson Education, Inc. All rights reserved. 1 Methods Called functions or procedures in other languages Modularize programs by separating its tasks.
Floating point numerical information. Previously discussed Recall that: A byte is a memory cell consisting of 8 switches and can store a binary number.
The scope of local variables. Murphy's Law The famous Murphy's Law says: Anything that can possibly go wrong, does. (Wikipedia page on Murphy's Law:
Working with arrays (we will use an array of double as example)
Introduction to programming in the Java programming language.
Introduction to Method. Example Java Method ( 1 ) The 2 types (kinds) of methods in Java Class methods Instance methods Methods can do more work than.
Assignment statements using the same variable in LHS and RHS.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
C++ Programming Basic Learning Prepared By The Smartpath Information systems
Mixing integer and floating point numbers in an arithmetic operation.
The Bisection Method. Introduction Bisection Method: Bisection Method = a numerical method in Mathematics to find a root of a given function.
The life time of local variables (in a method). Local variables Local variable: A local variable is used to store information that is relevant for the.
Using the while-statement to process data files. General procedure to access a data file General procedure in computer programming to read data from a.
The assignment expressions. The assignment operator in an assignment statement We have seen the assignment statement: Effect: var = expr; Stores the value.
The while-statement. The loop statements in Java What is a loop-statement: A loop-statement is a statement that repeatedly executes statements contained.
Arithmetic expressions containing Mathematical functions.
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Reading input from the console input. Java's console input The console is the terminal window that is running the Java program I.e., that's the terminal.
Introduction to array: why use arrays ?. Motivational example Problem: Write a program that reads in and stores away 5 double numbers After reading in.
Chapter 3: User-Defined Functions I
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Working with floating point expressions. Arithmetic expressions Using the arithmetic operators: and brackets (... ), we can construct arithmetic expression.
Boolean expressions, part 1: Compare operators. Compare operators Compare operators compare 2 numerical values and return a Boolean (logical) value A.
Simple algorithms on an array - compute sum and min.
The ++ and -- expressions. The ++ and -- operators You guessed it: The ++ and -- are operators that return a value.
CSIS 113A Lecture 5 Functions. Introduction to Functions  Building Blocks of Programs  Other terminology in other languages:  Procedures, subprograms,
Invoking methods in the Java library. Jargon: method invocation Terminology: Invoking a method = executing a method Other phrases with exactly the same.
The if-else statement. Introducing the if-else statement Programming problem: Re-write the a,b,c-formula program to solve for complex number solutions.
Chapter 7 User-Defined Methods.
Chapter 6: User-Defined Functions I
User-Defined Functions
The method invocation mechanism and the System Stack
The Boolean (logical) data type boolean
Classes, Objects and Methods
The for-statement.
Local variables and how to recognize them
Presentation transcript:

Introduction to Methods

Previously discussed There are similarities in make up of that can help you remember the construct of a class a class in the Java programming language and a book chapter in the English language

Previously discussed (cont.) Here is a graphical depiction of the resemblance:

Previously discussed (cont.) They are similar in the following manner: Class (in Java)Book Chapter (English) A class contains a number of related methods A chapter contains a number of related paragraphs A method contains a number of statements A paragraph contains a number of sentences A statement is the smallest unit of execution in the Java language A sentence is the smallest unit of readable text in the English language

The 2 types (kinds) of methods in Java Older (non-object-oriented) programming languages have only one type (kind) of method Newer programming languages (so called object-oriented languages, explained later) have 2 types (kinds) of methods: 1.Class methods 2.Instance methods

The 2 types (kinds) of methods in Java (cont.) We will now study the class methods We will delay the discussion of the instance methods for later (when we discuss abstract data types).

Why use methods in a computer program Convenience of methods: A statement can only accomplish a very small amount of work A method contains multiple statements. Therefore, a method is a more useful unit of program execution

Steps in using methods in a Java program How to use methods in a Java program: 1.First, you must define the method. How to define a method: Write down the steps (= statements) contained in the method. Attach a name to the steps (= statements)

Steps in using methods in a Java program (cont.) Notes: You only need to define a method once (Remember that in Java, you must define the method inside some class.)

Steps in using methods in a Java program (cont.) 2. After defining the method, you can then call a method using the name of the method This mechanism is called method invocation (an older term is procedure call) When a method is called, the statements inside the corresponding method are executed When all statements in the method has been executed, the execution will resume at the program location of the method call

Steps in using methods in a Java program (cont.) Note: You can invoke a method as many times as you wish

Example on how to use method: find the minimum of 2 floating point numbers We have previously seen an algorithm to find the smaller of 2 values x and y (see: /while2.html) if ( x < y ) { min = x; // x is the smaller value } else { min = y; // y is the smaller value }

Example on how to use method: find the minimum of 2 floating point numbers (cont.) We can create a method to perform the task of "finding the minimum of 2 value as follows: Remember: a method is always contained inside some class in Java Write down the statements in the algorithm Attach a name (e.g.: min) to the statements

Example on how to use method: find the minimum of 2 floating point numbers (cont.) Example: public class ToolBox // Methods must be contained inside a class { /* A method called "min" that contains the statements to find the smaller of 2 values a and b */ public static double min ( double a, double b ) { double min = 0;

Example on how to use method: find the minimum of 2 floating point numbers (cont.) if ( a < b ) { min = a; // a is the smaller value } else { min = b; // b is the smaller value } return(min); // Output of the method }... (You can define more methods inside a class) }

Example on how to use method: find the minimum of 2 floating point numbers (cont.) Explanation: The name of the method is min The method is contained inside the class named ToolBox The complete name of the "min" method is: ToolBox.min

Example on how to use method: find the minimum of 2 floating point numbers (cont.) How to use the method ToolBox.min: public class MyProgram { public static void main(String[] args) { double r; r = ToolBox.min( 1.0, 4.0 ); System.out.println(r); r = ToolBox.min( 3.7, -2.9 ); System.out.println(r); r = ToolBox.min( -9.9, 3.8 ); System.out.println(r); }

Example on how to use method: find the minimum of 2 floating point numbers (cont.) Notice the advantage of using methods: A non-savvy user that wants to use the ToolBox.min method does not need to know the statements contained inside the method ToolBox.min !!! A non-savvy user will only need to know the following in order to use the method: 1.The (complete) name of the method (i.e.: ToolBox.min) 2.What information the method needs to do the task (i.e.: 2 numbers) 3.What information the method returns to the user (i.e.: 1 number)

Example on how to use method: find the minimum of 2 floating point numbers (cont.) Notice the advantage of using methods: In fact, you were a non-savvy user of the methods in Java's Scanner class E.g.: You have used nextDouble() without knowing exactly what statements this method contains !

Example on how to use method: find the minimum of 2 floating point numbers (cont.) Example Program: (Demo above code) –Prog file: 1/MyProgram.java –File containing the min method: 1/ToolBox.java How to run the program: Right click on both links and save in a scratch directory To compile: javac MyProgram.java To run: java MyProgram

Example on how to use method: find the minimum of 2 floating point numbers (cont.) Output:

Example on how to use method: find the minimum of 2 floating point numbers (cont.) A note on the Java compiler: The Java compiler can detect that the program MyProgram.java uses a method ToolBox.min from the class ToolBox The Java compiler will try locate the file ToolBox.java and compile it automatically So you do not need to compile the Java program ToolBox.java explicitly --- the Java compiler will do that for you.

Method call (invocation) and return $64,000 Question: What happens in a method invocation ???

Method call (invocation) and return (cont.) We must first explain the effect of a return statement: public class ToolBox // Methods must be contained inside a class { /* A method called "min" that contains the statements to find the smaller of 2 values a and b */ public static double min ( double a, double b ) { double min = 0; if ( a < b ) {

Method call (invocation) and return (cont.) min = a; // a is the smaller value } else { min = b; // b is the smaller value } return(min); // ****** A "return" statement ******* }... (You can define more methods inside a class) }

Method call (invocation) and return (cont.) Syntax of a return statement: form 1: return ; form 2: return EXPRESSION ;

Method call (invocation) and return (cont.) Effect of a return statement: The return statement is used to terminate the execution of a method. If a return statement returns an EXPRESSION, then the value (= result) of the EXPRESSION will be used to replace the method call at the point of call. When the program executes a return statement, the method terminates (or exits) The execution will continue at the location where the method was called

Method call (invocation) and return (cont.) What happens in a method invocation: Java program: public class MyProgram { public static void main(String[] args) { double r; r = ToolBox.min( 1.0, 4.0 ); // Invokes the "ToolBox.min" method ! System.out.println(r); r = ToolBox.min( 3.7, -2.9 ); System.out.println(r); r = ToolBox.min( -9.9, 3.8 ); System.out.println(r); }

Method call (invocation) and return (cont.) The ToolBox.min method: public class ToolBox // Methods must be contained inside a class { /* A method called "min" that contains the statements to find the smaller of 2 values a and b */ public static double min ( double a, double b ) { double min = 0; if ( a < b ) { min = a; // a is the smaller value } else { min = b; // b is the smaller value } return(min); // **** Return statement **** }

Method call (invocation) and return (cont.) Execution of the program: Program starts executing in the main method:

Method call (invocation) and return (cont.) The method invocation ToolBox.min(1.0, 4.0) transfers the program execution to the method ToolBox.min

Method call (invocation) and return (cont.) The min method executes and reaches the return statement

Method call (invocation) and return (cont.) Notice that the variable min = 1.0 when the return statement is executed.

Method call (invocation) and return (cont.) The return statement transfers program execution back to the point of invocation

Method call (invocation) and return (cont.) After the method returns, the returned value (1.0) will effectively replace the method invocation In other words, the assignment statement that will be executed is: r = 1.0 ;

Method call (invocation) and return (cont.) Bottom line: The variable r will be assigned with the minimum of the 2 values passed to the ToolBox.min method !!!

Defining a class method Syntax used to define a method:

Defining a class method (cont.) Note: the construct must appear inside some class, so it will look like this:

Defining a class method (cont.) The keyword public tells the Java compiler that we are defining something that had no access restriction The "something" can be one of two things: In other words, you can only define 2 kinds of things inside a class: methods or variables A method, or A variable Explanation:

Defining a class method (cont.) The keyword static tells the Java compiler that we are defining a class typed method (or variable). Note: If you omit the keyword static, you will define an instance method (or variable) which will be discussed later.

Defining a class method (cont.) The RETURN-TYPE is a Java data type (e.g., int, double, etc.) The RETURN-TYPE specifies the type of the data that is returned by the method.

Defining a class method (cont.) The method-Name is an identifier that is used to identify this method. You use the method-Name to identify the method in the method invocation

Defining a class method (cont.) The pair of brackets (.... ) tells the Java compiler that you want to define a method. You can in fact define 2 different things inside a class: We will discuss variables defined inside a class later in the course. methods variables

Defining a class method (cont.) A definition without the brackets (... ) will define a variable !!! Notice how the Java compiler can tell the difference:

Defining a class method (cont.) The FORMAL-PARAMETER-LIST is a comma-separated list of parameter variables that is passed (= given to) the method as additional information The items in the FORMAL-PARAMETER- LIST has the following form: TYPE variable-name

Defining a class method (cont.) A formal parameter variable is initialized with the value given in the method call It is a way to pass information to the method so it can use the information to perform its designated task

Defining a class method (cont.) The method body completes the method definition The method body is a block (enclosed between {... }) Within the method body, you can write any number of the following things: statements variable definitions --- variables defined inside a method body are called local variables

Defining a class method (cont.) The method header The method header is the first part of the method definition without the method body

Defining a class method (cont.) Example:

Alternative example on defining the min method In the previous example, we put the definition of the min method inside a new class named ToolBox Alternatively, we can define the min method inside the same class as the main method - like this: public class MyProgram { public static double min ( double a, double b ) { double min = 0; if ( a < b ) { min = a; // a is the smaller value

Alternative example on defining the min method (cont.) } else { min = b; // b is the smaller value } return(min); // **** Return statement **** } public static void main(String[] args) { double r; r = MyProgran.min( 1.0, 4.0 ); // The name is now: "MyProgram.min" ! System.out.println(r); r = MyProgram.min( 3.7, -2.9 ); System.out.println(r); r = MyProgram.min( -9.9, 3.8 ); System.out.println(r); }

Alternative example on defining the min method (cont.) Note: Because the definition of min method is contained inside the class MyProgram, the name the method is now: We must use this new name to invoke the min method. MyProgram.min

Alternative example on defining the min method (cont.) Example Program: (Demo above code) –Prog file: 2/MyProgram.java How to run the program: Right click on both links and save in a scratch directory To compile: javac MyProgram.java To run: java MyProgram

A short hand for invoking a method defined inside the same class Notice that in this example: public class MyProgram { public static double min ( double a, double b ) { double m = 0; if ( a < b ) { m = a; // a is the smaller value } else { m = b; // b is the smaller value

A short hand for invoking a method defined inside the same class (cont.) } return(m); // **** Return statement **** } public static void main(String[] args) { double r; r = MyProgram.min( 1.0, 4.0 ); // The name is now: "MyProgram.min" ! System.out.println(r); r = MyProgram.min( 3.7, -2.9 ); System.out.println(r); r = MyProgram.min( -9.9, 3.8 ); System.out.println(r); }

A short hand for invoking a method defined inside the same class (cont.) contains 2 methods The method main invokes (calls) the method min. min main

A short hand for invoking a method defined inside the same class (cont.) Short hand method invocation: We can reference a method defined inside the same class without using the class name

A short hand for invoking a method defined inside the same class (cont.) Example: public class MyProgram { public static double min ( double a, double b ) { double m = 0; if ( a < b ) { m = a; // a is the smaller value } else { m = b; // b is the smaller value }

A short hand for invoking a method defined inside the same class (cont.) return(m); // **** Return statement **** } public static void main(String[] args) { double r; r = min( 1.0, 4.0 ); // ****** Shorthand name "min" used System.out.println(r); r = min( 3.7, -2.9 ); System.out.println(r); r = min( -9.9, 3.8 ); System.out.println(r); }

A short hand for invoking a method defined inside the same class (cont.) Example Program: (Demo above code) –Prog file Scope1.java: 3/MyProgram.java How to run the program: Right click on link and save in a scratch directory To compile: javac MyProgram.java To run: java MyProgram

Organizing methods in classes Fact: But: A method can be placed in any class Imagine placing books on a number of shelves You can place any book on any shelf Then it very difficult to find a desired book !!!

Organizing methods in classes (cont.) Advice: to allow easily location of methods Place related methods inside the same class Give the class a meaningful name Give each method a meaningful name also

Organizing methods in classes (cont.) Example from Java: The sin, cos, tan, log, exp, sqrt, etc methods are all defined inside the same class The name of this class is Math That's why we use: to invoke the sqrt method !!! Math.sqrt(... )

Remaining topics in Methods We still need to discuss some important topics related to methods: 1.The scope and lifetime of local variables 2.How parameters are passed to methods.