64
Introduction to Methods

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

Embed Size (px)

Citation preview

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: http://mathcs.emory.edu/~cheung/Courses/170/Syllabus/07/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:

http://mathcs.emory.edu/~cheung/Courses/170/Syllabus/08/Progs/1/MyProgram.java

– File containing the min method:

http://mathcs.emory.edu/~cheung/Courses/170/Syllabus/08/Progs/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:

1.0

-2.9

-9.9

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:

http://mathcs.emory.edu/~cheung/Courses/170/Syllabus/08/Progs/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:

http://mathcs.emory.edu/~cheung/Courses/170/Syllabus/08/Progs/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.