Programming with Java Module 4 Methods and Functions Theoretical Part Contents 1 Module overview 3 2 Methods 3 2.1 Methods without return value (procedures).............. 3 2.2 Functions with return value (functions)................. 4 2.3 Methods with parameters......................... 5 3 Methods of the class Math 6 4 Method Overloading 7 4.1 Scope: visibility of variables........................ 8 5 Recursion 9 5.1 Example 1: Factorial............................. 9 5.2 Example 2: Fibonacci............................ 9 6 Error handling with exceptions 10 6.1 Throwing exceptions............................ 11
Keywords Methods Subroutine Procedure Function Parameter Return value Return Type Visibility of Variables Overloading Recursion Exception Random Number Modularity Authors: Lukas Fässler, Barbara Scheuner, David Sichau E-Mail: et@ethz.ch Date: 18 July 2018 Version: 1.1 Hash: d2eb005 The authors try the best to provide an error free work, however there still might be some errors. The Authors are thankful for your feedback and suggestions. This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/ 2
1 Module overview An entire problem is broken down into separate parts by the modular concept. In this module, you will learn how commands can be combined into subprograms (or subroutines). Subroutines are functional units which can be invoked from several positions in a program. This way, a program part only has to be developed and tested once whereby the programming effort is reduced and the program code is shortened. If data are passed by invoking the subroutine, they are called parameters. In many programming languages, two variants of subroutines are distinguished: those with a return value (functions) and those without a return value (procedures). In Java, all subroutines that can have parameters and return values are referred to as methods. 2 Methods A method in Java consists of a head (or signature) with the modification public static 1, the return type, the name, the parameters and the body in the curly brackets {. The execution of a Java application usually starts in the main method which often only invoke other methods. 2.1 Methods without return value (procedures) You have already used functions without return value: for example the function System.out.println() which inserts a line break. However, you can also write your own methods which fulfil a task determined by you. Methods without return value looks as follows: Notation: void methodname() { //Signature of the method // Commands The word void indicates that no return value is expected. The empty brackets () means that no paramters are passed. 1 The meaning of the modifications results from the object-orientation of Java and will not be discussed in this book. 3
The following class contains the main method with the name main and the method output which is invoked in the main method: public class ProcedureTest{ public static void main(string[] args){ output(); public static void output(){ //Signature of the method System.out.println("the method was executed"); 2.2 Functions with return value (functions) Methods with return value are used to win a result of the commands in the function. The data type of the return value is directly in front of the method name. It must be ensured that a value of the corresponding type is returned in the method. To return a value, the word return is used. Notation: return type methodname() { //Signature of the method // Commands The following class contains a main method and a further method getanswerthat is invoked in the main method: public class ProcedureTest{ public static void main(string[] args){ int value = getanswer(); public static int getanswer(){ //Signature of the method return 42; The return value in the example above is of type Integer. It has to be taken into account that it is mandatory to return a value in each case. 4
boolean hello(){ int i = 1; if (i == 1){ return true; else { System.out.println("will never occur"); Even if the else-case will never occur, you have to bear in mind that something would also be returned in this case. Correct would be: boolean hello(){ int i=1; if (i==1){ return true; else { System.out.println("will never occur"); return false; 2.3 Methods with parameters We can also pass values to functions. Such values passed to a function are called parameters. We have to declare the variables received (input variable) in the header of the function definition to be able to pass values to your function. When calling the function, the parameter is passed to the input variable. Both types of methods (i.e. procedures and functions) can demand parameters in the signature. Parameters are variables whose initializing happens when the methods is invoked and which are necessary for executing the task of the method. void addandoutput(int x, int y){ int z = x + y; System.out.println("Sum: "+z); This method can be invoked, for example, with the values 3 and 2: 5
addandoutput(3,2); Methods with return value can now also return a value. int add(int x, int y){ int z = x + y; return z; This method can be invoked as follows: int resultat = add(3,2); The return value is stored in the variable result whose data type is equal to the return type. 3 Methods of the class Math The class Math provides some methods which realize mathematical functions. All these methods are functions since they have a return value (the result of the calculation). They usually except one or two numbers as parameters. public class TestMath{ public static void main(string[] args){ double x= 19.7; double y= 20.3; double largernumber = Math.max(x,y); double smallernumber = Math.min(x,y); double rounddown = Math.ceil(x); A method without parameter of the class Math is the function Math.random(). This function returns a random number between 0 and 1 whereby the number can be equal to 0 but it is always smaller than 1. This function enables us to generate a random integer between 1 and x. This can be done as follows: 1. Generating a random number between 0 and 1. 6
2. Multiplication of this number with x. This results in a floating-point number between 0 and x. 3. Rounding. // Generating a random number between 0 and 99 by rounding down int randomnumber1 = (int)(math.random()*100); // Generating a random number between 0 and 100 by rounding long randomnumber2 = Math.round(Math.random()*100); 4 Method Overloading Method Overloading is a feature that allows a class to have two or more methods having same name, if their parameters are different. However, different returns values alone are not sufficient. If two methods have the same name but they contain different types or numbers of parameter, the method is called overloaded. A popular example that you have often used are the methods print() and println(), respectively. We can pass values of type string, int, double, etc. to this method. For you as a user it looks like as you always invoke the same methods. However, you invoke different methods corresponding to the data type. Therefore, we can write the two following methods with identical name line in the same class: // Signature with one parameter public static void line(int x){ for (int i=0; i<x; i++){ System.out.print( - ); // Signature with two parameters public static void line(int x, char c){ for (int i=0; i<x; i++){ System.out.print(c); If you invoke the method with only one parameter value, the first method is used and with two values, the second one: line(8); line(19, - ); 7
4.1 Scope: visibility of variables Variables have a limited lifetime. Some variables are only deleted when the program is terminated, others are already deleted at an earlier point. A variable is always visible in the command block (see module 2) or class in which it was declared. A variable declared at the beginning of the method is also deleted when the program ends. If the value of these variables is required later on, it needs to be returned to the invoking function. public class visibilityvariables{ public static int global = 20; public static void main(string[] args){ System.out.println("Values between 1 and "+ global); output(); public static void output(){ int random = 0; for (int i=0; i<30; i++){ random = (int) (Math.random() * global) + 1; The variable global is visible within the whole class. The variable random is only visible within the method output and the variable i only within the loop. If we used the commented line, the following code would result in an error message because the variable random is not visible in the main method: public class VisibilityVariables2{ public static void output(){ int random = (int) (Math.random() * global) + 1; public static void main(string[] args){ output(); // System.out.println("Values between 1 and "+ zufall); 8
5 Recursion A recursion is a method which calls itself. To avoid that the method calls itself infinitely, which has the same consequences as an infinite loop, a termination condition which stops the self-invoking is necessary. To programme a recursion, you have to determine two elements: Basic case: in this case, the result of the calculation is already known. This case corresponds to the termination condition of the recursion. Recursive call: you have to determine how the recursive call shall be done. 5.1 Example 1: Factorial The calculation of the factorial f(x) = x! of x can be realized by using a recursive method. Basic case: the factorial of the values 0 and 1 is 1. Recursion: x! = x (x 1)! for x > 1 int factorial(int x){ if ((x == 0) (x == 1){ // Basic case return 1; else { return x * factorial(x-1); // Recursive call 5.2 Example 2: Fibonacci A further popular example is the recursion of the Fibonacci sequence. This infinite sequence of integers starts with 0 and 1. The next number results from the sum of the two preciding numbers: Therefore, the sequence is 0, 1, 1, 2, 3, 5, 8,... For the Fibonacci sequence, two recursive calls are necessary in each step: f(n) = f(n 1) + f(n 2) for n 2 with the start values f(1) = 1 and f(0) = 0. Basic case: for the case that n is equal to 1 or 0, we know that 0 and 1, respectively, has to be returned. Recursion: we call the function again for all the other case whereby we decrease the passed values by 1 and 2. 9
int fibonacci(int n) { if (n == 0){ // Basic case 1 return 0; else if (n == 1){ // Basic case 2 return 1; else { // recursive call twice return (fibonacci(n-1) + fibonacci(n-2)); Note that the function fibonacci in example 2 calls itself twice. We also call it cascading recursion. In example 1, only a single self-invoking call occurs what is also referred to as a linear recursive. 6 Error handling with exceptions Exceptions are caused by exceptional situations during the program execution. Exception handling shall prevent abnormal program terminations. Try-catch-commands enable us to catch and handle exceptions within a method. Maybe you wanted to convert a text into a number by mistake or access an array index that was outside the bounds of the array. Exceptions do not need appear on the console. One also can catch them and search for a solution to the problem. Exceptions can be catched as follows: try { // anything that might cause an error catch (Exception c) { // Solution of the problem 10
Here, the user might enter a character instead of an integer. This incorrect input can be handled as follows: public static void main(string[] args) { Scanner scan = new Scanner(System.in); int number = 0; System.out.println("Please enter an integer."); String value = scan.nextline(); try { number = Integer.parseInt(value); catch (Exception e){ System.out.println("This is not an integer"); number = 0; 6.1 Throwing exceptions You also can use the construct of exception yourself. If you want to communicate an error in your own method, you can throw an exception. The command throw new Exception() provokes an error. The signature of a method that is able to provoke an exception has to be extended by throw Exception. public class ExceptionTester{ public static void main(string[] args) { try { tester(-3); catch (Exception e) { System.out.println(e.getMessage()); public static void tester(int x) throws Exception{ if (x < 0){ throw new Exception(); 11