PAC Introduction to Methods Professor: Evan Korth New York University.

41
PAC Introduction to Methods Professor: Evan Korth New York University

Transcript of PAC Introduction to Methods Professor: Evan Korth New York University.

Page 1: PAC Introduction to Methods Professor: Evan Korth New York University.

PACIntroduction to Methods

Professor: Evan KorthNew York University

Page 2: PAC Introduction to Methods Professor: Evan Korth New York University.

Prentice Hall, Inc. All rights reserved.

6.1 Introduction

• Modules– Small pieces of a problem

• e.g., divide and conquer

– Facilitate design, implementation, operation and maintenance of large programs

Page 3: PAC Introduction to Methods Professor: Evan Korth New York University.

Prentice Hall, Inc. All rights reserved.

6.2 Program Modules in Java

• Modules in Java– Methods (procedural programming)

– Classes (object oriented programming)

• Java API provides several modules• Programmers can also create modules

– e.g., programmer-defined methods

• Methods– Invoked by a method call

– Returns a result to calling method (caller)

– Similar to a boss (caller) asking a worker (called method) to complete a task.

• The boss method delegates certain jobs to specific methods.

Modified by Evan Korth

Page 4: PAC Introduction to Methods Professor: Evan Korth New York University.

Prentice Hall, Inc. All rights reserved.

Fig. 6.1 Hierarchical boss-method/worker-method relationship.

boss

worker1 worker2 worker3

worker4 worker5

Page 5: PAC Introduction to Methods Professor: Evan Korth New York University.

Examples of methods

• A method that determines the maximum of two numbers.

• A method that sorts a list of names• A method that opens a file from the file system.• A method that reads from the open file.• A method that opens a new socket to the internet.• A method that reads from that socket.• A method that parses an integer value from a

String.• A method that gets a String from the user.

Page 6: PAC Introduction to Methods Professor: Evan Korth New York University.

Important concept #1

• Divide and Conquer: Break large programs into a series of smaller modules

– Helps manage complexity

– Makes it easier to build large programs

– Makes it easier to debug programs

Page 7: PAC Introduction to Methods Professor: Evan Korth New York University.

Important concept #2

• Abstraction: Most of the time, you need to know what a method does, but not how it actually does it.– Also helps manage complexity

– You use other people’s code without knowing how it does it’s job.

Page 8: PAC Introduction to Methods Professor: Evan Korth New York University.

Using Static methods in the Java API

Page 9: PAC Introduction to Methods Professor: Evan Korth New York University.

Prentice Hall, Inc. All rights reserved.

6.3 Math-Class Methods

• Class java.lang.Math– Provides common mathematical calculations

– Calculate the square root of 900.0:• Math.sqrt( 900.0 )

– Method sqrt belongs to class Math• Dot (.) allows access to method sqrt

– The argument 900.0 is located inside parentheses

Page 10: PAC Introduction to Methods Professor: Evan Korth New York University.

Prentice Hall, Inc. All rights reserved.

Method Description Example abs( x ) absolute value of x (this method also has float, int

and long versions) abs( 23.7 ) is 23.7 abs( 0.0 ) is 0.0 abs( -23.7 ) is 23.7

ceil( x ) rounds x to the smallest integer not less than x ceil( 9.2 ) is 10.0 ceil( -9.8 ) is -9.0

cos( x ) trigonometric cosine of x (x is in radians) cos( 0.0 ) is 1.0 exp( x ) exponential method ex exp( 1.0 ) is 2.71828

exp( 2.0 ) is 7.38906 floor( x ) rounds x to the largest integer not greater than x floor( 9.2 ) is 9.0

floor( -9.8 ) is -10.0 log( x ) natural logarithm of x (base e) log( Math.E ) is 1.0

log( Math.E * Math.E ) is 2.0 max( x, y ) larger value of x and y (this method also has float,

int and long versions) max( 2.3, 12.7 ) is 12.7 max( -2.3, -12.7 ) is -2.3

min( x, y ) smaller value of x and y (this method also has float, int and long versions)

min( 2.3, 12.7 ) is 2.3 min( -2.3, -12.7 ) is -12.7

pow( x, y ) x raised to the power y (xy) pow( 2.0, 7.0 ) is 128.0 pow( 9.0, 0.5 ) is 3.0

sin( x ) trigonometric sine of x (x is in radians) sin( 0.0 ) is 0.0 sqrt( x ) square root of x sqrt( 900.0 ) is 30.0

sqrt( 9.0 ) is 3.0 tan( x ) trigonometric tangent of x (x is in radians) tan( 0.0 ) is 0.0 Fig. 6.2 Math-class methods.

Page 11: PAC Introduction to Methods Professor: Evan Korth New York University.

Prentice Hall, Inc. All rights reserved.

6.4 Methods Declarations

• Methods– Allow programmers to modularize programs

• Makes program development more manageable

• Software reusability

• Avoid repeating code

– Local variables• Declared in method declaration

– Parameters• Communicates information between methods via method calls

Page 12: PAC Introduction to Methods Professor: Evan Korth New York University.

Prentice Hall, Inc. All rights reserved.

6.4 Method Declarations (Cont.)

• Programmers can write customized methods

Page 13: PAC Introduction to Methods Professor: Evan Korth New York University.

Line 9: method call to square

line 16: header for method square. States that we have a method that accepts one integer as a parameter and returns one integer

line 18: returns the value y * y

1 // Fig. 6.3: SquareIntegers.java2 // Creating and using a programmer-defined method.3 public class SquareIntegers {

4 public static void main (String args[])5 {6 int result; // store result of call to method square

7 // loop 10 times8 for ( int counter = 1; counter <= 10; counter++ ) {9 result = square( counter ); // method call

10 // print the result of one call to the method 11 System.out.println ("The square of " + counter + " is " + 12 result );

13 } // end for

14 } // end method main()

15 // square method declaration

16 public static int square( int y ) 17 { 18 return y * y; // return square of y

19 } // end method square

20 } // end class SquareIntegers

Method square returns int that result stores

Modified by Evan Korth

2003 Prentice Hall, Inc.All rights reserved.

Method square returns the square of y

y is the parameter of method square

Page 14: PAC Introduction to Methods Professor: Evan Korth New York University.

Prentice Hall, Inc. All rights reserved.

6.4 Method Declarations (cont.)

• General format of method declaration:

modifiers return-value-type method-name( parameter1, …, parameterN ){ declarations and statements}

• Method can also return values: return expression;

Page 15: PAC Introduction to Methods Professor: Evan Korth New York University.

random numbers

• Often we want our programs to generate random numbers.– games of chance

– testing without user interaction

• java.lang.Math provides a method which can be used to generate random numbers

Page 16: PAC Introduction to Methods Professor: Evan Korth New York University.

Prentice Hall, Inc. All rights reserved.

Random-Number Generation

• Java random-number generators

– Math.random()

• Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.

– What if we want to generate random integers?

Page 17: PAC Introduction to Methods Professor: Evan Korth New York University.

Prentice Hall, Inc. All rights reserved.

Random-Number Generation

– ( int ) ( Math.random() * 6 )

• Produces integers from 0 - 5

Page 18: PAC Introduction to Methods Professor: Evan Korth New York University.

Prentice Hall, Inc.All rights reserved.

Outline

RandomIntegers.java

Line 16Produce integers in range 1-6

Line 16Math.random returns doubles. We cast the double as an int

1 // Fig. 6.7: RandomIntegers.java2 // Shifted, scaled random integers.3 import javax.swing.JOptionPane;4 5 public class RandomIntegers {6 7 public static void main( String args[] )8 {9 int value;10 String output = "";11 12 // loop 20 times13 for ( int counter = 1; counter <= 20; counter++ ) {14 15 // pick random integer between 1 and 6 16 value = 1 + ( int ) ( Math.random() * 6 );17 18 output += value + " "; // append value to output19 20 // if counter divisible by 5, append newline to String output21 if ( counter % 5 == 0 )22 output += "\n";23 24 } // end for25

Produce integers in range 1-6

Math.random returns doubles. We cast the double as an int

Page 19: PAC Introduction to Methods Professor: Evan Korth New York University.

Prentice Hall, Inc.All rights reserved.

Outline

RandomIntegers.java

26 JOptionPane.showMessageDialog( null, output, 27 "20 Random Numbers from 1 to 6", 28 JOptionPane.INFORMATION_MESSAGE );29 30 System.exit( 0 ); // terminate application31 32 } // end main33 34 } // end class RandomIntegers

Page 20: PAC Introduction to Methods Professor: Evan Korth New York University.

Prentice Hall, Inc.All rights reserved.

Outline

RollDie.java

Line 14Produce integers in range 1-6

Lines 17-43Increment appropriate frequency counter, depending on randomly generated number

1 // Fig. 6.8: RollDie.java2 // Roll a six-sided die 6000 times.3 import javax.swing.*;4 5 public class RollDie {6 7 public static void main( String args[] )8 {9 int frequency1 = 0, frequency2 = 0, frequency3 = 0,10 frequency4 = 0, frequency5 = 0, frequency6 = 0, face;11 12 // summarize results13 for ( int roll = 1; roll <= 6000; roll++ ) {14 face = 1 + ( int ) ( Math.random() * 6 );15 16 // determine roll value and increment appropriate counter17 switch ( face ) {18 19 case 1:20 ++frequency1;21 break; 22 23 case 2:24 ++frequency2;25 break;26 27 case 3:28 ++frequency3;29 break;30

Produce integers in range 1-6

Increment appropriate frequency counter, depending on randomly generated number

Page 21: PAC Introduction to Methods Professor: Evan Korth New York University.

Prentice Hall, Inc.All rights reserved.

Outline

RollDie.java

31 case 4:32 ++frequency4;33 break;34 35 case 5:36 ++frequency5;37 break;38 39 case 6:40 ++frequency6;41 break;42 43 } // end switch44 45 } // end for46 47 JTextArea outputArea = new JTextArea();48 49 outputArea.setText( "Face\tFrequency" + "\n1\t" + frequency1 + 50 "\n2\t" + frequency2 + "\n3\t" + frequency3 + 51 "\n4\t" + frequency4 + "\n5\t" + frequency5 + 52 "\n6\t" + frequency6 );53 54 JOptionPane.showMessageDialog( null, outputArea,55 "Rolling a Die 6000 Times", JOptionPane.INFORMATION_MESSAGE );56 57 System.exit( 0 ); // terminate application58 59 } // end main60 61 } // end class RollDie

This is different from the example I showed in the compiler. I left it this way to show you that showMessageDialog() can take other objects besides String for the message. Remember the API.

You do not need to know JTextArea for this class!

Page 22: PAC Introduction to Methods Professor: Evan Korth New York University.

Prentice Hall, Inc. All rights reserved.

Page 23: PAC Introduction to Methods Professor: Evan Korth New York University.

User defined methods

Page 24: PAC Introduction to Methods Professor: Evan Korth New York University.

Prentice Hall, Inc. All rights reserved.

User defined Method Declarations

• General format of method declaration:

modifiers return-value-type method-name( parameter1, …, parameterN ){ declarations and statements}

• Method can also return values: return expression;

Page 25: PAC Introduction to Methods Professor: Evan Korth New York University.

Naming your methods

• As with variables naming methods is important• You should give your methods names which

clearly describe what the function is doing– helps debugging

– helps others read your code

• Same rules as naming variables– E.g. public static double calculateTax( int sale )

• When you write about a method in an explanation use the parenthesis to indicate you are referencing a method (as opposed to a regular variable):– E.g. //call squareInteger() to calculate the square

Page 26: PAC Introduction to Methods Professor: Evan Korth New York University.

Good programming with methods

• A method should do one and only one useful action– If you see names for your method that suggest multiple

actions then it’s time to break it up into separate functions; for example,

calculateTaxAndPrintReturnAndSaveFile(); -ugh

• If you do something more than once in a program, you should write a method for that action.

• If you have written a method to do something in one project, and you need to do the same action in another project, you should reuse the method.– In Java this is usually accomplished by using classes which

we will cover later this semester.

Page 27: PAC Introduction to Methods Professor: Evan Korth New York University.

Return Value Types

• You can only return one value from a method.

• Returning void– void: means nothing

– A method that returns void therefore returns nothing.

– Hence, there is no need for the optional return statement. But using one can force early exit from the method.

– Example: public static void printIntro (int n);

Page 28: PAC Introduction to Methods Professor: Evan Korth New York University.

Parameter Data Types

• Unlike return values, you can pass as many parameters as you like.

• To pass more than one parameter, you need to separate the parameters with commas.

public static int maximum (int x, int y)

{

/*body*/

}

Page 29: PAC Introduction to Methods Professor: Evan Korth New York University.

Warning

• Unlike declaring variables, you must specifically state the type for multiple variables– For example

takeTwoFloats( float x, y )

is incorrect

– Instead you must write

takeTwoFloats(float x, float y)

Page 30: PAC Introduction to Methods Professor: Evan Korth New York University.

No parameters

• You can also have a method that accepts no parameters. In such case, you would just have an empty parameter list.

E.g.

public static int rollDie ()

public static void printIntro ()

Page 31: PAC Introduction to Methods Professor: Evan Korth New York University.

Prentice Hall, Inc. All rights reserved.

6.5 Argument Promotion

• Coercion of arguments

– Forcing arguments to appropriate type to pass to method

• e.g., System.out.println( Math.sqrt( 4 ) );

– Evaluates Math.sqrt( 4 )

– Then evaluates System.out.println()

• Promotion rules

– Specify how to convert types without data loss

Page 32: PAC Introduction to Methods Professor: Evan Korth New York University.

Prentice Hall, Inc. All rights reserved.

Type Valid promotions double None float double long float or double int long, float or double char int, long, float or double short int, long, float or double byte short, int, long, float or double boolean None (boolean values are not considered to be

numbers in Java) Fig. 6.5 Allowed promotions for primitive types.

Page 33: PAC Introduction to Methods Professor: Evan Korth New York University.

Prentice Hall, Inc. All rights reserved.

6.15 Method Overloading

• Method overloading– Several methods of the same name

– Different parameter set for each method• Number of parameters

• Parameter types

– The Java compiler determines which method to use based on the parameters.

– Can also be used in conjunction with argument coercion.• The combination can lead to ambiguous invocation which is

an error

Page 34: PAC Introduction to Methods Professor: Evan Korth New York University.

Understanding Scope

Page 35: PAC Introduction to Methods Professor: Evan Korth New York University.

Scope

• Determines where the variable can be referenced in a program.

• By understanding scope, you can make your programs:– more modular

– easier to debug

Page 36: PAC Introduction to Methods Professor: Evan Korth New York University.

Prentice Hall, Inc. All rights reserved.

6.9 Scope of Declarations

• Scope– Portion of the program that can reference an entity by its

name

– Basic scope rules• Scope of a parameter declaration

– The entire method

• Scope of a local-variable declaration

– From where it is declared until the end of the block it is declared in

• Scope of a local-variable declaration that appears in the initialization section of a for statement’s header

– The entire code block of the for loop

Modified by Evan Korth

Page 37: PAC Introduction to Methods Professor: Evan Korth New York University.

pass by value

• In Java when a parameter is passed to a method and the variable is modified by that method, the value does not change upon return to the calling method (there are exceptions to this including passing arrays and passing object references)

• This is not true in all programming languages.

Page 38: PAC Introduction to Methods Professor: Evan Korth New York University.

Good Programming Habits

• Pick a method name that strongly, completely and clearly describes what the function does or returns– E.g. verb-plus-object or description of returned value

(getters, setters, predicates are object orientated naming conventions)

• Make sure your actual parameters (i.e. the actual data you pass to a method) matches the data type the method expects.

• Make sure you use all the parameters in your method; if not, lose the ones you don’t use.

• Document any assumptions about your parameters!

Page 39: PAC Introduction to Methods Professor: Evan Korth New York University.

More Good Programming Habits

• Limit the number of a method’s parameters to approximately seven– Studies have shown that people can’t keep track of more

than seven pieces of info at once

– (e.g. 7 digit phone numbers for a reason)

• If a method is to return a value, make sure it returns something under all possible circumstances. Actually, Java will enforce this for you.

Page 40: PAC Introduction to Methods Professor: Evan Korth New York University.

Superman program

• Superman needs a program to print S’s of various size. You should have one method that prints the horizontal lines and one method that prints the vertical lines. Write the whole program.

– Vertical lines can be in the first or last column and are width/2 – 1 characters tall.

– For example, an S of size 6 would look like:

SSSSSS

S

S

SSSSSS

S

S

SSSSSS

Page 41: PAC Introduction to Methods Professor: Evan Korth New York University.

RaiseIntToPower

• Write a method raiseIntToPower that takes two integers, n and k, and returns nk. For example the method call:

raiseIntToPower (2, 4); would return 16 Hints: – What value should you use to initialize the return value?

– 24 = 2 X 2 X 2 X 2

– You can assume n and k are non-negative