Think Twice Code Once The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2005 Khaleel I. Shaheen Computer Programming, I Laboratory Manual Experiment #7 Methods
What are Methods? Methods can be used to define reusable code and organize and simplify coding. A method is a collection of statements grouped together to perform an operation. In previous labs, we have used a number of known methods like println and random, nextint, etc. These methods are defined the Java language, so we can directly call and use them, and it is clear this makes our work easier. In this lab we are going to learn how to define our own methods. Defining a Method A method definition consists of its method name, parameters, return value type, and body. The syntax for defining a method is as follows: modifier returnvaluetype methodname(list of parameters) { // Method body; Now, let's get a look at the following method that returns the maximum of two numbers: public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; Using public and static keywords are not part of the format, but right now, and as we will be calling our methods from the main method, we will use static in method definition. The method header specifies the modifiers, return value type, method name, and parameters of the method. The returnvaluetype is the data type of the value the method returns. Some methods perform desired operations without returning a value. In this case, the returnvaluetype is the keyword void. 2
If a method returns a value, it is called a value-returning method; otherwise it is called a void method. for example, Integer.parseInt() method returns integer data type, and println() method does not return anything, so we call it void method. Method name: the name we will use to call our method, this name must be a valid variable. The naming convention for method name is like variable name; first word starts with lower case letter, and rest of words start with upper case letters. Parameters list: the variables defined in the method header are known as formal parameters or simply parameters. A parameter is like a placeholder: provide an interface for providing input to method. The parameter list refers to the method s type, order, and number of the parameters. The method name and the parameter list together constitute the method signature. Method could take zero or more parameters, for example, println method takes one parameter as string and prints that string on the console, while Math.random method doesn t take any parameters Method body: statements of the method, these statements are executed when method is called. return keyword: when a method has return type (not void), we have to terminate it using return keyword followed by the variable, value or expression that represents the value which the method should return. Now, let's try to call the max method Calling a Method Calling a method executes the code in the method. There are two ways to call a method, depending on whether the method returns a value or not. If a method returns a value, a call to the method is usually treated as a value. For example, int larger = max(3, 4); Another example of a call that is treated as a value is 3
System.out.println(max(3, 4)); If a method returns void, a call to the method must be a statement. For example, the method println returns void. The following call is a statement: System.out.println("Welcome to Java!"); Note: A value-returning method can also be invoked as a statement in Java. In this case, the caller simply ignores the return value. Ex: Write a method that take two numbers, x and y, and returns the sum of number from x to y. Then use the method to print the sum of numbers in ranges [0,10], [1,100], [100, 150]. Solution: System.out.println(sumRange(0, 10)); System.out.println(sumRange(1, 100)); System.out.println(sumRange(100, 150)); public static int sumrange(int x, int y) { int sum = 0; for (int i = x; i <= y; i++) { sum += i; return sum; void Method A void method does not return a value. We should use void keyword for the method when we do not want to return values from it. The following program defines a method named printgrade and invokes it to print the grade for a given score. 4
System.out.print("The grade is "); printgrade(78.5); System.out.print("The grade is "); printgrade(59.5); public static void printgrade(double score) { if (score >= 90.0) { System.out.println('A'); else if (score >= 80.0) { System.out.println('B'); else if (score >= 70.0) { System.out.println('C'); else if (score >= 60.0) { System.out.println('D'); else { System.out.println('F'); While the following method returns the value of a grade for a given score. System.out.println("The grade is " + getgrade(78.5)); System.out.println("The grade is " + getgrade(59.5)); public static char getgrade(double score) { char grade; if (score >= 90.0) { grade = 'A'; else if (score >= 80.0) { grade = 'B'; else if (score >= 70.0) { grade = 'C'; else if (score >= 60.0) { grade = 'D'; else { grade = 'F'; return grade; 5
Value-returning methods could be used directly in a statement like this: System.out.println("The grade is " + getgrade(78.5)); The value returned from the method is used in the statement. Also, we can assign the returned value to a variable then use that variable when needed. For example: char grade = getgrade(78.5); System.out.println("The grade is " + grade); Passing Arguments by Values The arguments are passed by value to parameters when invoking a method. The power of a method is its ability to work with parameters. When calling a method, you need to provide arguments, which must be given in the same order as their respective parameters in the method signature. This is known as parameter order association. When you invoke a method with an argument, the value of the argument is passed to the parameter. This is referred to as pass-by-value. If the argument is a variable rather than a literal value, the value of the variable is passed to the parameter. The variable is not affected, regardless of the changes made to the parameter inside the method. Consider the following code: int x = 1; System.out.println("Before the call, x is " + x); increment(x); System.out.println("After the call, x is " + x); public static void increment(int n) { n++; System.out.println("n inside the method is " + n); 6
If you compile and run the code above, the value of x will remain 1 after calling increment method, because the value of x was copied into n, then the value of n was incremented, but x itself had never affected, because we did not pass x, rather we passed its value. Overloading Methods In Java, two or more different methods can have the same name if their parameter types or number are different. That means that you can give the same name to more than one method if they have either a different number of parameters or different types in their parameters. Methods with same name and different signatures are called overloaded methods. Scanner input = new Scanner(System.in); int a = input.nextint(); int b = input.nextint(); int c = input.nextint(); int d = input.nextint(); double avg2 = avg(a, b); double avg3 = avg(a, b, c); double avg4 = avg(a, b, c, d); System.out.println(avg2); System.out.println(avg3); System.out.println(avg4); public static double avg(int a, int b) { return (a + b) / 2.0; public static double avg(int a, int b, int c) { return (a + b + c) / 3.0; public static double avg(long a, long b, long c, long d) { return (a + b + c + d) / 4.0; Overloading methods can make programs clearer and more readable. Methods that perform the same function with different types of parameters should be given the same name. 7
Ex: Write a function that returns the absolute value of a number. If the function was called without any arguments, it should return the absolute of 1. Solution: public static int abs(int x) { if (x < 0) return x * -1; return x; public static int abs() { return abs(1); The Scope of Variables Scope of a variable is the part of the program where the variable is accessible. A variable declared inside the class is called a global variable as it can be used by any method in the class. A variable defined inside a method is referred to as a local variable. The scope of a local variable starts from its declaration and continues to the end of the block that contains the variable. A local variable must be declared and assigned a value before it can be used. A parameter is actually a local variable. The scope of a method parameter covers the entire method. Any variables created inside of a loop are LOCAL TO THE LOOP. This means that once you exit the loop, the variable can no longer be accessed! 8
public class Scope { int globalvariable; // globalvariable can be accessed anywhere in the class int localvariable; for (int i = 0; i < 10; i++) { // i can only be accessed inside the loop // i can not be accessed here public static void othermethod(int parameter) { // parameter is a local variable. // Scope of a method parameter covers the entire method. int localvariable; // different variable that is local to this method only Lab Work Ex1: Write a method that prints the maximum of three variables. The variables may be integers, double, char or String. public static int max(int a, int b, int c) { if (a > b && a > c) return a; else if (b > a && b > c) return b; else return c; public static double max(double a, double b, double c) { if (a > b && a > c) return a; else if (b > a && b > c) return b; else return c; 9
public static char max(char a, char b, char c) { if (a > b && a > c) return a; else if (b > a && b > c) return b; else return c; public static String max(string a, String b, String c) { if (a.compareto(b) > 0 && a.compareto(c) > 0) return a; else if (b.compareto(a) > 0 && b.compareto(c) > 0) return b; else return c; Homework 1. Write a method, reversedigit, that takes an integer as a parameter and returns the number with its digits reversed. For example, the value of reversedigit(12345) is 54321. Also, write a program to test your method. 2. Write a method int count_vowels(string str) that returns a count of all vowels in the string str. Vowels are the letters a, e, i, o, and u, and their upper case variants. Good Luck 10