Methods (Functions) CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1
What Is a Method? A method is a mechanism for allowing a piece of code to be executed more than once, in a safe way. Examples: s.length(), s.indexof(s2), Math.floor(3.4) Syntax Communication with the calling line. Signature of the method Parameters Return value (when appropriate) 2
import java.util.scanner; public static double square(double number) double result = number * number; return result; Scanner in = new Scanner(System.in); System.out.printf("Please enter a number: "); double N = in.nextdouble(); double N_square = square(n); System.out.printf("%.2f squared = %.2f\n", N, N_square); 3
Terminology: Methods/Functions In Java, the term methods is the one mainly used. In some other languages, the term functions is more common. In some languages (e.g., C++) methods and functions have minor differences in meaning. In this course, I will use the two terms (methods and functions) as synonyms. 4
A First Example Here we see our first example of a function. It is called square. Its job is to compute the square of a number. import java.util.scanner; public static double square(double number) double result = number * number; return result; Scanner in = new Scanner(System.in); System.out.printf("Please enter a number: "); double N = in.nextdouble(); double N_square = square(n); System.out.printf("%.2f squared = %.2f\n", N, N_square); 5
What Is a Function A function is a piece of code that does a specific job. Usually (but not always) the job is to compute something. Examples: Computing the square of a number. Determining if an number is prime. Computing the number of digits of a number. import java.util.scanner; public static double square(double number) double result = number * number; return result; Scanner in = new Scanner(System.in); System.out.printf("Please enter a number: "); double N = in.nextdouble(); double N_square = square(n); System.out.printf("%.2f squared = %.2f\n", N, N_square); Counting the number of vowels in a string. 6
How to Write a Function Specify a name, like square. import java.util.scanner; public static double square(double number) double result = number * number; return result; function name Scanner in = new Scanner(System.in); System.out.printf("Please enter a number: "); double N = in.nextdouble(); double N_square = square(n); System.out.printf("%.2f squared = %.2f\n", N, N_square); 7
How to Write a Function Specify a name, like square. Specify the inputs (called parameters). The parameters are the input that the function needs in order to compute an output. For example, what does the square function take as input? import java.util.scanner; public static double square(double number) double result = number * number; return result; Scanner in = new Scanner(System.in); System.out.printf("Please enter a number: "); double N = in.nextdouble(); double N_square = square(n); System.out.printf("%.2f squared = %.2f\n", N, N_square); 8
How to Write a Function Specify a name, like square. Specify the inputs (called parameters). The parameters are the input that the function needs in order to compute an output. For example, what does the square function take as input? A number. import java.util.scanner; public static double square(double number) double result = number * number; return result; Scanner in = new Scanner(System.in); System.out.printf("Please enter a number: "); double N = in.nextdouble(); parameter(s) double N_square = square(n); System.out.printf("%.2f squared = %.2f\n", N, N_square); We can have functions with 0, 1, or more arguments. We will see examples later. 9
How to Write a Function Specify a name, like square. Specify the inputs (called parameters). Specify the return type of the function. What is the type of the value that the function computes? In other words, what values are legal and illegal for the output of the function? import java.util.scanner; public static double square(double number) double result = number * number; return result; Scanner in = new Scanner(System.in); System.out.printf("Please enter a number: "); double N = in.nextdouble(); return type double N_square = square(n); System.out.printf("%.2f squared = %.2f\n", N, N_square); 10
How to Write a Function Specify a name, like square. Specify the inputs (called parameters). Specify the return type of the function. Specify what the function does. This is what we call the body of the function. import java.util.scanner; public static double square(double number) double result = number * number; return result; Scanner in = new Scanner(System.in); System.out.printf("Please enter a number: "); double N = in.nextdouble(); body double N_square = square(n); System.out.printf("%.2f squared = %.2f\n", N, N_square); 11
How to Write a Function Specify a name, like square. Specify the inputs (called parameters). Specify the return type of the function. Specify what the function does. This is what we call the body of the function. import java.util.scanner; public static double square(double number) double result = number * number; return result; Scanner in = new Scanner(System.in); System.out.printf("Please enter a number: "); double N = in.nextdouble(); return statement Specify what value the function returns, using one or more return statements. 12 double N_square = square(n); System.out.printf("%.2f squared = %.2f\n", N, N_square);
Using a Function (Function Calls) Once you have written a function, you can use it anywhere in your code, by doing a function call. import java.util.scanner; public static double square(double number) double result = number * number; return result; Scanner in = new Scanner(System.in); System.out.printf("Please enter a number: "); double N = in.nextdouble(); function call double N_square = square(n); System.out.printf("%.2f squared = %.2f\n", N, N_square); 13
Using a Function (Function Calls) Once you have written a function, you can use it anywhere in your code, by doing a function call. When you call a function, you must: Provide the appropriate argument(s). import java.util.scanner; public static double square(double number) double result = number * number; return result; Scanner in = new Scanner(System.in); System.out.printf("Please enter a number: "); double N = in.nextdouble(); argument(s) double N_square = square(n); System.out.printf("%.2f squared = %.2f\n", N, N_square); 14
Using a Function (Function Calls) Once you have written a function, you can use it anywhere in your code, by doing a function call. When you call a function, you must: Provide the appropriate argument(s). Use the return value appropriately. import java.util.scanner; public static double square(double number) double result = number * number; return result; Scanner in = new Scanner(System.in); System.out.printf("Please enter a number: "); double N = in.nextdouble(); storing the return value double N_square = square(n); System.out.printf("%.2f squared = %.2f\n", N, N_square); 15
Using the Return Value In the square function, the return value is a double. You can use this value in any way that you can use any double number. Examples: You can store the return value in a variable. import java.util.scanner; public static double square(double number) double result = number * number; return result; Scanner in = new Scanner(System.in); System.out.printf("Please enter a number: "); double N = in.nextdouble(); storing the return value in a variable double N_square = square(n); System.out.printf("%.2f squared = %.2f\n", N, N_square); 16
Using the Return Value In the square function, the return value is a double. You can use this value in any way that you can use any double number. Examples: You can store the return value in a variable. You can print the return value directly. import java.util.scanner; public static double square(double number) double result = number * number; return result; Scanner in = new Scanner(System.in); System.out.printf("Please enter a number: "); double N = in.nextdouble(); printing the return value directly System.out.printf("%.2f squared = %.2f\n", N, square(n)); 17
Using the Return Value In the square function, the return value is a double. You can use this value in any way that you can use any double number. Examples: You can store the return value in a variable. You can print the return value directly. You can use it as part of a more complicated expression. import java.util.scanner; public static double square(double number) double result = number * number; return result; Scanner in = new Scanner(System.in); System.out.printf("Please enter a number: "); double N = in.nextdouble(); double my_var = 18 + square(n); using the return value in an expression System.out.printf("result = %.2f\n", my_var); 18
Using the Return Value In the square function, the return value is a double. You can use this value in any way that you can use any double number. Examples: You can store the return value in a variable. You can print the return value directly. You can use it as part of a more complicated expression. You can use it as an argument for another function call. import java.util.scanner; public static double square(double number) double result = number * number; return result; Scanner in = new Scanner(System.in); System.out.printf("Please enter a number: "); double N = in.nextdouble(); the return value is used as argument for another function call double my_var = 18 + square(square(n)); System.out.printf("result = %.2f\n", my_var); 19
Function Calls You can call a function as many times as you like. On the next slide, we call the square function three times. 20
import java.util.scanner; Example: Calling the square function three times. public static double square(double number) double result = number * number; return result; Scanner in = new Scanner(System.in); System.out.printf("Please enter a number M: "); double M = in.nextdouble(); System.out.printf("Please enter a number N: "); double N = in.nextdouble(); double M_square = square(m); System.out.printf("%.2f squared = %.2f\n", M, M_square); double N_square = square(n); System.out.printf("%.2f squared = %.2f\n", N, N_square); double MN_square = square(m*n); System.out.printf("%.2f squared = %.2f\n", M*N, M*N_square); 21
Example: Printing Prime Numbers Write a program that: Asks the user to enter an integer N. Prints all prime integers from 2 up to (and including) N. 22
Example: Printing Prime Numbers Write a program that: Asks the user to enter an integer N. Prints all prime integers from 2 up to (and including) N. First step: Write the basic structure of the program. Put placeholders where more detail is needed. import java.util.scanner; Scanner in = new Scanner(System.in); System.out.printf("Enter an integer: "); int N = in.nextint(); for (int i = 2; i <= N; i++) if i is prime System.out.printf("%d\n", i); 23
Example: Printing Prime Numbers Write a program that: Asks the user to enter an integer N. Prints all prime integers from 2 up to (and including) N. Second step: Identify functions that can be used to complete the program. import java.util.scanner; Scanner in = new Scanner(System.in); System.out.printf("Enter an integer: "); int N = in.nextint(); for (int i = 2; i <= N; i++) if i is prime System.out.printf("%d\n", i); 24
Example: Printing Prime Numbers Write a program that: Asks the user to enter an integer N. Prints all prime integers from 2 up to (and including) N. We can use a function is_prime to check if i is prime. Arguments? import java.util.scanner; Scanner in = new Scanner(System.in); System.out.printf("Enter an integer: "); int N = in.nextint(); for (int i = 2; i <= N; i++) if i is prime System.out.printf("%d\n", i); Return type? 25
Example: Printing Prime Numbers Write a program that: Asks the user to enter an integer N. Prints all prime integers from 2 up to (and including) N. We can use a function is_prime to check if i is prime. Arguments? an integer import java.util.scanner; Scanner in = new Scanner(System.in); System.out.printf("Enter an integer: "); int N = in.nextint(); for (int i = 2; i <= N; i++) if i is prime System.out.printf("%d\n", i); Return type? boolean 26
Example: Printing Prime Numbers Write a program that: Asks the user to enter an integer N. Prints all prime integers from 2 up to (and including) N. Step 3: use the function. We have not written the function yet, but that is OK. Obviously, the program will not run until we write the function. import java.util.scanner; Scanner in = new Scanner(System.in); System.out.printf("Enter an integer: "); int N = in.nextint(); for (int i = 2; i <= N; i++) if (is_prime(i)) System.out.printf("%d\n", i); 27
import java.util.scanner; Write a program that: Asks the user to enter an integer N. Prints all prime integers from 2 up to (and including) N. Step 4: write the function. public static boolean is_prime(int N) for (int i = 2; i < N; i++) if (N % i == 0) return false; return true; Scanner in = new Scanner(System.in); System.out.printf("Enter an integer: "); int N = in.nextint(); for (int i = 2; i <= N; i++) if (is_prime(i)) System.out.printf("%d\n", i); 28
Output: Enter an integer: 80 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 import java.util.scanner; public static boolean is_prime(int N) for (int i = 2; i < N; i++) if (N % i == 0) return false; return true; Scanner in = new Scanner(System.in); System.out.printf("Enter an integer: "); int N = in.nextint(); for (int i = 2; i <= N; i++) if (is_prime(i)) System.out.printf("%d\n", i); 29
Why Do We Need Functions To write better code: More correct, easier to read/write/change. To write complicated code. Functions help us organize code. YOU CANNOT WRITE NON-TRIVIAL PROGRAMS IF YOU DO NOT USE FUNCTIONS 30
Example: Prime Numbers, Again Write a program that: Asks the user to enter an integer N. Prints out the smallest prime number greater than or equal to N. (problem solving: if lost, think of a simpler property) 31
Example: Prime Numbers, Again Write a program that: Asks the user to enter an integer N. Prints out the smallest prime number greater than or equal to N. First step: Write the basic structure of the program. Put placeholders where more detail is needed. import java.util.scanner; Scanner in = new Scanner(System.in); System.out.printf("Enter an integer: "); int N = in.nextint(); int i = N; while (i is not prime) i++; System.out.printf("%d\n", i); 32
Example: Prime Numbers, Again Write a program that: Asks the user to enter an integer N. Prints out the smallest prime number greater than or equal to N. Second step: Identify functions that can be used to complete the program. We can use the is_prime function again!!! import java.util.scanner; Scanner in = new Scanner(System.in); System.out.printf("Enter an integer: "); int N = in.nextint(); int i = N; while (is_prime(i) == false) i++; System.out.printf("%d\n", i); 33
import java.util.scanner; Write a program that: Asks the user to enter an integer N. Prints out the smallest prime number greater than or equal to N. To complete the program, we can just use the is_prime function we already have. Functions make it really easy to re-use code!!! public static boolean is_prime(int N) for (int i = 2; i < N; i++) if (N % i == 0) return false; return true; Scanner in = new Scanner(System.in); System.out.printf("Enter an integer: "); int N = in.nextint(); while (is_prime(n) == false) N++; System.out.printf("%d\n", N); 34
Example Output: Enter an integer: 1000000 1000003 Example Output: Enter an integer: 123456789 123456791 Example Output: Enter an integer: 7500 7507 import java.util.scanner; public static boolean is_prime(int N) for (int i = 2; i < N; i++) if (N % i == 0) return false; return true; Scanner in = new Scanner(System.in); System.out.printf("Enter an integer: "); int N = in.nextint(); while (is_prime(n) == false) N++; System.out.printf("%d\n", N); 35
Making Code Easier to Read In lots of programs, we need to perform a task many times. Copying and pasting code can work, but has disadvantages: The resulting code can look long and ugly. If we make a mistake, we end up copying and pasting the mistake many times. Fixing such mistakes, that have been copied and pasted many times, can be a pain. 36
Example: Repeated Printing Write a program that: Asks the user to enter a string S. Asks the user to enter a number N. Prints N times string S. Example Output: Enter string S: hello Enter integer N: 5 hello hello hello hello hello 37
Example: Repeated Printing Write a program that: Asks the user to enter a string S. Asks the user to enter a number N. Prints N times string S. Let's write a function, that: takes as input a string S and an integer N. prints the string N times. import java.util.scanner; Scanner in = new Scanner(System.in); System.out.printf("Enter string S: "); String S = in.next(); System.out.printf("Enter integer N: "); int N = in.nextint(); print String S repeatedly, N times. 38
Example: Repeated Printing The complete program is shown on the right. Function repeat_print has two features we have not seen before: It takes two arguments. It returns nothing. import java.util.scanner; public static void repeat_print(string message, int times) for (int i = 0; i < times; i++) System.out.printf("%s\n", message); Scanner in = new Scanner(System.in); System.out.printf("Enter string S: "); String S = in.next(); System.out.printf("Enter integer N: "); int N = in.nextint(); repeat_print(s, N); 39
A Function That Returns Nothing Function repeat_print does something useful. However, we do not want any value returned from the function. In that case, we specify the return type of the function as void. import java.util.scanner; public static void repeat_print(string message, int times) for (int i = 0; i < times; i++) System.out.printf("%s\n", message); Scanner in = new Scanner(System.in); System.out.printf("Enter string S: "); String S = in.next(); System.out.printf("Enter integer N: "); int N = in.nextint(); repeat_print(s, N); 40
The main Function When Java executes a program, how does Java know where to start? Every program must have a function called main, such that: It takes one argument, of type String []. We will understand this type in our next topic, when we do arrays. the return type is void. Until we saw how to write functions, all our code used to go to main. Now that we have started using functions, the main code will be a relatively small part of the program. Functions will do the bulk of the work. 41
Function Arguments Functions have arguments. To call a function XYZ, you write something like : XYZ(argument_1,, argument_n) How would you know how many arguments to use? 42
Function Arguments Functions have arguments. To call a function XYZ, you write something like: XYZ(argument_1,, argument_n) How would you know how many arguments to use? From the function definition, which (among other things) defines EXACTLY: how many arguments to use. the type of each argument. the order of the arguments. public static type XYZ(type 1 arg_1,, type_n arg_n) 43
Executing a Function Call When the body of the function starts executing, the only variables visible to the function are: the arguments. variables defined in the body of the function. 44
What Will This Program Do? public static void foo(string var1, String var2) System.out.printf("var1 = %s\n", var1); String var1 = "hello"; String var2 = "goodbye"; String var3 = "earth"; String var4 = "moon"; foo(var3, var4); 45
Step-by-step Execution public static void foo(string var1, String var2) System.out.printf("var1 = %s\n", var1); variables in main: String var1 = "hello"; String var2 = "goodbye"; String var3 = "earth"; String var4 = "moon"; foo(var3, var4); Current line 46
Step-by-step Execution public static void foo(string var1, String var2) System.out.printf("var1 = %s\n", var1); variables in main: String var1 = "hello"; String var2 = "goodbye"; String var3 = "earth"; String var4 = "moon"; foo(var3, var4); First line to execute: 47
Step-by-step Execution public static void foo(string var1, String var2) System.out.printf("var1 = %s\n", var1); variables in main: var1 = "hello" String var1 = "hello"; String var2 = "goodbye"; String var3 = "earth"; String var4 = "moon"; foo(var3, var4); First line creates variable var1 48
Step-by-step Execution public static void foo(string var1, String var2) System.out.printf("var1 = %s\n", var1); variables in main: var1 = "hello" String var1 = "hello"; String var2 = "goodbye"; String var3 = "earth"; String var4 = "moon"; foo(var3, var4); Next line to execute: 49
Step-by-step Execution public static void foo(string var1, String var2) System.out.printf("var1 = %s\n", var1); variables in main: var1 = "hello" var2 = "goodbye" String var1 = "hello"; String var2 = "goodbye"; String var3 = "earth"; String var4 = "moon"; foo(var3, var4); Next line to execute: 50
Step-by-step Execution public static void foo(string var1, String var2) System.out.printf("var1 = %s\n", var1); variables in main: var1 = "hello" var2 = "goodbye" var3 = "earth" String var1 = "hello"; String var2 = "goodbye"; String var3 = "earth"; String var4 = "moon"; foo(var3, var4); Next line to execute: 51
Step-by-step Execution public static void foo(string var1, String var2) System.out.printf("var1 = %s\n", var1); variables in main: var1 = "hello" var2 = "goodbye" var3 = "earth" var4 = "moon" String var1 = "hello"; String var2 = "goodbye"; String var3 = "earth"; String var4 = "moon"; foo(var3, var4); Next line to execute: function call 52
Step-by-step Execution public static void foo(string var1, String var2) System.out.printf("var1 = %s\n", var1); String var1 = "hello"; String var2 = "goodbye"; String var3 = "earth"; String var4 = "moon"; foo(var3, var4); variables in main: var1 = "hello" var2 = "goodbye" var3 = "earth" var4 = "moon" variables in foo: var1 =??? var2 =??? Next line to execute: function call. First, assign values to arguments. 53
Step-by-step Execution public static void foo(string var1, String var2) System.out.printf("var1 = %s\n", var1); String var1 = "hello"; String var2 = "goodbye"; String var3 = "earth"; String var4 = "moon"; foo(var3, var4); variables in main: var1 = "hello" var2 = "goodbye" var3 = "earth" var4 = "moon" variables in foo: var1 = "earth" var2 = "moon" Next line to execute: function call. First, assign values to arguments. 54
Step-by-step Execution public static void foo(string var1, String var2) System.out.printf("var1 = %s\n", var1); String var1 = "hello"; String var2 = "goodbye"; String var3 = "earth"; String var4 = "moon"; foo(var3, var4); variables in main: var1 = "hello" var2 = "goodbye" var3 = "earth" var4 = "moon" variables in foo: var1 = "earth" var2 = "moon" Next line to execute: How does Java know which var1 to print? 55
Step-by-step Execution public static void foo(string var1, String var2) System.out.printf("var1 = %s\n", var1); String var1 = "hello"; String var2 = "goodbye"; String var3 = "earth"; String var4 = "moon"; foo(var3, var4); variables in main: var1 = "hello" var2 = "goodbye" var3 = "earth" var4 = "moon" variables in foo: var1 = "earth" var2 = "moon" Next line to execute: Currently executing the body of foo. Only the variables of foo are visible. earth" is printed. 56
Step-by-step Execution public static void foo(string var1, String var2) System.out.printf("var1 = %s\n", var1); variables in main: var1 = "hello" var2 = "goodbye" var3 = "earth" var4 = "moon" variables in foo: String var1 = "hello"; String var2 = "goodbye"; String var3 = "earth"; String var4 = "moon"; foo(var3, var4); var1 = "earth var2 = "moon" Next line to execute: "moon" is printed. 57
Step-by-step Execution public static void foo(string var1, String var2) System.out.printf("var1 = %s\n", var1); variables in main: var1 = "hello" var2 = "goodbye" var3 = "earth" var4 = "moon" variables in foo: String var1 = "hello"; String var2 = "goodbye"; String var3 = "earth"; String var4 = "moon"; foo(var3, var4); var1 = "earth" var2 = "moon" Next line to execute: Which line comes next? 58
Step-by-step Execution public static void foo(string var1, String var2) System.out.printf("var1 = %s\n", var1); variables in main: var1 = "hello" var2 = "goodbye" var3 = "earth" var4 = "moon" String var1 = "hello"; String var2 = "goodbye"; String var3 = "earth"; String var4 = "moon"; foo(var3, var4); Next line to execute: Done with the function call. The variables of foo disappear. 59
Step-by-step Execution public static void foo(string var1, String var2) System.out.printf("var1 = %s\n", var1); variables in main: var1 = "hello" var2 = "goodbye" var3 = "earth" var4 = "moon" String var1 = "hello"; String var2 = "goodbye"; String var3 = "earth"; String var4 = "moon"; foo(var3, var4); Next line to execute: "goodbye" is printed. 60
Summary of Program Output public static void foo(string var1, String var2) System.out.printf("var1 = %s\n", var1); String var1 = "hello"; String var2 = "goodbye"; String var3 = "earth"; String var4 = "moon"; foo(var3, var4); Output: var1 = earth var2 = moon var2 = goodbye 61
Practice Write functions Based on problem description: Write a function that takes [as argument] a string S and returns the sum of the ASCII code of the characters in it. Write a function that takes 2 strings, a piece size, p_sz, and merges the strings in chunks of p_sz. Write a function that takes [as argument] a list L and returns the sum of the elements in L. If L has strings, it should return the concatenation of all the strings. Write a fct that takes two arguments: a String, s, and a char,c, and removes all the occurrences of c from the string s. Test cases: s = aaxyaj, c = a // s = aaaaaaaa, c = a // s = aaa, c = a return a new string with the modifications. Based on your own choice. 62