8-Methods.pptx
Document Details
Uploaded by IndulgentPelican
University of Doha for Science and Technology
Full Transcript
Methods - Subprograms COM136 – Software Development 1 1 Learning Outcomes • At the end of this lecture you should • Understand the concepts associated with the method construct and their implementation in Java. • Understand the difference between action and value methods. • Learn how to use param...
Methods - Subprograms COM136 – Software Development 1 1 Learning Outcomes • At the end of this lecture you should • Understand the concepts associated with the method construct and their implementation in Java. • Understand the difference between action and value methods. • Learn how to use parameters in Java methods • Understand what is meant by call-by-value parameter passing • Understand what is meant by scope and duration of variables 2 Breaking larger programs down • Two popular approaches to program design, especially when writing larger programs • Structured programming – divide initial problem into smaller sub-problems. Implement algorithms for each sub-problem and combine into overall solution. • Object Oriented programming – modern approach which will be covered in module COM139 next semester. • We are using the structured approach, but the algorithm development skills we are learning are required in both approaches 3 Sub-programs and Methods • Algorithms we have created have used the basic programming constructs of • Sequence • Selection • Repetition • But larger programs may consist of multiple algorithms • We can use methods (sub-programs) to implement multiple algorithms in our solutions 4 Sub-programs and Methods • Advantages of methods • Allow us to provide solutions to larger problems. • Different people can work on different methods simultaneously. • Methods can be reused. • Using methods enhances the programs readability because it reduces complexity. • Methods are also integral to the object oriented approach covered next semester. 5 Some methods we’ve already seen • Which classes do each of these belong to? • What type of parameters can we give to them? • How do we use them? • nextInt() • getInt(“Enter an Integer”) • println(“Hello!”) • main(String args[]) • mars() • Pizza base recipe (Not Java!) 6 Answers • nextInt() • Class: Scanner • parameters: none • Action: returns integer value from text available to scanner or throws exception if number cannot be parsed • getInt (“Enter an integer”) • Class: Console • parameter: A String • Action: Writes String parameter to console and gets integer input from user 7 Answers (cont) • println (“Hello!”) • Class: System.out • parameters: a String • Action: Writes String to console • main(String args[]) • Class: Defined by the programmer • parameter: An array of strings • Action: Used to implement any algorithm you choose 8 Answers (cont) • mars() • Class: Defined by us • parameter: None • Action: Writes a message on the screen • Pizza base recipe (Not Java!) • Class: The recipe book (collection of algorithms) • parameter: List of ingredients • Action: Makes a pizza base 9 How do we use (call) these methods? • Following method is called automatically when you run the program main(String args[]) • Following methods are called by using their name (with parameters, if any) as a statement as shown below System.out.println(“Hello!”); mars(); 10 Note • When the method isn’t in the class from which it is being called, we must include its class name in the call, as with following: • System.out.println(“Hello”); • These are called static methods and we will learn more about static and non-static methods next semester 11 Calling methods (continued) • The following method call is different! int age = Console.getInt(“Enter your age”); integer returned by Console.getInt method is assigned to variable age • We call it by using its name, as with the others, but the call is an expression, not a statement. • To capture the result, we must either • assign it to a variable, as above • pass it to another method as a parameter 12 What do these method calls do? System.out.println( “Hello world” ); 1. Call to System.out.println(..) evaluates the parameter ‘a string’ 2. And result of method is to displays this string to the console System.out.println( Console.getString(“Name?”) ); 1. Call to System.out.println(..) evaluates the parameter, this time its ‘a call to a value returning method’ Console.getString(..) 2. Remember, getString(..) returns a user entered string and this 3. String is passed to System.out.println method which displays the string 13 So we’ve got two types of methods: • Ones that carry out an action (have a side-effect) these have return type void - indicates that they don’t return anything e.g. public static void main(String args[]) public static void mars() public static void println(String prompt) 14 … and ones that return a value • Ones that return a value have a non-void return type e.g. Console.getInt(“…”) • What is the return type of this method? - an int • How do we know? Well we read the documentation for this library method 15 Here’s an example of each type // action method – prints square public static void squareAction(int y) { System.out.println( y * y ); } // value method – returns square public static int squareValue(int y) { return y * y; } 16 Example of Usage • Calling action method System.out.print(“Square of 6 is “); squareAction(6); prints 36 to console • Calling value method int sq = squareValue(6); System.out.println(“Square of 6 is “ + sq); • Alternative way to call value method System.out.println(“Square of 6 is “ + squareValue(6) ); squareValue returns 36 which is added to string “Square of 6 is “ and printed to console by println command 17 Note • A method with return type void (an action method) must not return a value; it may have a return statement without an expression return; • …but this is simply used to terminate the method. • A method with a return type other than void must contain a return statement with an expression of the return type. 18 Method Parameters • Method header indicates if the method accepts any parameters and returns a value (value method) or no value (action method) • For example public static int getInt(String prompt) One String parameter No parameters public static void mars() One int parameter public static void squareAction(int a) 19 Some examples • Consider the following method declarations public static void method1() public static void method2(int x, double y) public static int method3(char c) • Which of following are valid method calls method1(); method2(2); int a = method3(‘B’); method2(2, 4.0); method2(method3(‘A’),4.56); => => => => => Ok Error Ok Ok Ok 20 Parameters • Parameters declared in heading of the method are called formal parameters. • Parameters supplied when the method is called are actual parameters. • Actual and formal parameters must correspond in number, order and type. • ‘Correspond in type’ does not necessarily mean they must be the same type. For example an int parameter could be passed to a method that expects a double (but not vice a versa). 21 Parameter Passing • What happens when a method is called? int x = 4; squareAction(x); • The value of the actual parameter (variable x (4)) is copied into the formal parameter (variable y)within squareAction method overleaf. • This mechanism is known as call by value • Variable y behaves similarly to an initialised local variable within squareAction. • Any changes to y do not affect x 22 Call By Value parameter passing public static int squareValue( int y ) { y = y * y; return y; } public static void main(String[] args) { int x = 2; Memory x 2 y 24 System.out.println( “Square of “ + x + “ is “ + squareValue(x) ); } 23 More on Parameters • What will squareAction write to the console? squareAction(5); => 25 squareAction(2 + 4); => 36 squareAction(Console.getInt(“Num?”)); => ?? 24 Method Composition • The squareValue method returns a value which may itself be used as a parameter to another method. • What is the value of r in following expressions? 81 9 int r = squareValue( squareValue(3) ); 256 16 81 4 int r = squareValue( squareValue( squareValue(2) ) ); 256 25 Duration of identifiers • The duration of an identifier is the time during which it exists in memory. • Parameters and local variables declared in a method body have automatic duration; • created when their declaration is reached, • destroyed when the block they are in, delimited by { } terminates. 26 Scope of identifiers • The scope of an identifier is that part of the program in which it may be referenced. • A variable declared in a block, that is, between any pair of { } has block scope - it can only be used between its declaration and the end of that block. 27 Duration and Scope public static void sample(int x) { int y = 0; while (y < x) { int z = y; System.out.println(z); y = y + 1 ; } Scope of z } Scope of x and y 28 Variable Scope and Duration Guidelines • Always declare a variable as locally as possiblethus limiting likelihood of being accidentally changed • Consider following swap algorithms Ok Better int temp; ... if (a > b) { temp = a; a = b; b = temp; } if (a > b) { int temp = a; a = b; b = temp; } Temp only declared in block where it is required 29 Flow of Execution • When a method is called, execution of the current method is halted while the called method is executing. • When the called method terminates, execution of the calling method resumes with next statement main() { statement1; method1(); statement3; } method1() { statement1; method2(); statement3; } method2() { statement1 statement2 statement3; } 30 Guidelines for creating methods • Each method should perform one defined task. • Typically a method should contain no more than a page of code. • A program will typically consist of a collection of methods including the main method. • Methods should be tested separately and then added to the main program. • Using methods makes a program easier to develop, debug and understand. 31 An Example We define a value method to prompt a user to return a vat code 0-2 which we can use in our main method public class VatCalculator { // input number in range bound by low and high public static int getVatCode() { int code = Console.getInt(“Enter vat code 0-2”); while (code < 0 || code > 2) { num = Console.getInt(“Enter vat code 0-2”); } return code; } // PTO ... 32 An Example We can now call this method ... public static void main(String args[]) { // accept a valid vat code (0-2) int code = getVatCode(); double price = Console.getDouble(“Enter price £”); // now apply the vat based on the code if (code == 1) { // } ... ... } // end of main } // end of class 33 An Improved version We could make this method more “reusable” (less specific) as follows public class NumInput { // input number in range bound by low and high public static int getInRange(int low, int high, String prompt) { int num = Console.getInt(prompt); while (num < low || num > high) { num = Console.getInt(prompt); } return num; } … other input methods can go here } 34 An Example To use this new class and method we would call the method as follows int num = NumInput.getInRange(0,2,”Enter Code 02”); Note: If class is in same directory as calling class then we can simply call it Otherwise we need to add the directory containing the class to the Java CLASSPATH and import (like uulib) Topic for next semester! 35 An Example The Vat program calls getInRange which exists in the separate NumInput class public class VatCalculator { public static void main(String[] args) { // ensure value of code is 0,1 or 2 int code = NumInput.getInRange(0,2,”Enter(0-2)”); double price = Console.getDouble(“Enter price £”); ... // note how we call this method as its in this class file double vat = calcVatBasedOnCode(code, price); System.out.println(“Vat £ “ + vat); } // ... PTO 36 An Example // sub-program (method) to calc vat public static double calcVatBasedOnCode(int code, double price) { double vat = 0; // default is 0.0 vat if (code == 2) { vat = price * 0.2; // ideally use constant not 0.2 } else if (code == 1) { vat = price * 0.05; // ideally use constant not 0.05 } return vat; } } // end of class 37 Summary • In this section we have covered: • The concepts associated with the method construct and their implementation in Java. • The difference between action and value methods. • How to use parameters in Java methods • What is meant by call-by-value parameter passing • What is meant by scope and duration of variables 38 An extreme “functional” Example public class VatCalc { public static void main(String[] args) { double vat = calcVatBasedOnCode( NumInput.getInRange(0, 2, ”Enter(0-2)” ), Console.getDouble(“Enter price £”) ); System.out.println(“Vat £ “ + vat); } 39 An extreme “functional” Example 2 public class VatCalc { public static void main(String[] args) { System.out.println(“Vat £ “ + calcVatBasedOnCode( NumInput.getInRange(0, 2,”Enter Code 0-2”), Console.getDouble(“Enter price £”) ) ); } 40