Islamic University of Gaza Faculty of Engineering Computer Engineering Department Computer Programming Lab (ECOM 2114) Created by Eng: Mohammed Alokshiya Modified by Eng: Mohammed Abdualal Lab 8 Methods Eng. Mohammed Abdualal November 1, 2015
A method is a collection of statements that are grouped together to perform an operation. In the previous labs, we have introduced a number of known methods like println and random, nextint, etc. these methods are previously written by developers of Java, so we can directly call and use them, and it is clear this makes our work easier. To write a method, use the following definition format: Define a Method [public] [static] ReturnType methodname (param_1, param_2,..., param_n) { // Method Body return returnvalue; 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 contents of method definition are the following: static: because we will be calling our methods from the main method which is static, we should define our methods as static. Return type: data type of the value this method will return, for example, Integer.parseInt() method returns integer data type, and println method does not return anything, so we call it void method. To define a void method, use void keyword instead of return type in definition. 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. List of parameters: method parameters provide an interface for providing input to method, those parameters are variables specified by data type and name, separated by commas. Method could take zero to infinity parameters, for example, println method 2
takes one parameter as string and prints that string on the console. Method body: statements of the method, these statements are executed when method is called. return: 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 method should return. The following example shows how to find the maximum of two numbers using method calling. max Method public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; You can write the previous method in a class, before the main method of after it. Then you can call it by its name from any other methods like main method: Calling max Method from main method public static void main(string[] args) { Scanner input = new Scanner(System.in); int a = input.nextint(); int b = input.nextint(); int maxnum = max(a, b); System.out.println(maxNum); From the previous code, you can notice the following: No method is defined in the body of another one, so we define additional methods out of the block of main method, but is still in the block of the class. Method calling is simple and straightforward, all we have to do is to specify method name and pass the parameters. When method is called, the value of a is copied into matching method parameter which is num1, similarly, 3
the value of b is copied into num2, so when result is calculated, it contains the sum of num1 and num2. Another example to find the greatest common devisor of two number using the Euclidean algorithm (You should be familiar with Euclidean algorithm from Discrete Math Course) GCD Method public static int GCD(int a, int b) { int temp; while (b > 0) { temp = a % b; a = b; b = temp; return a; public static void main(string[] args) { int result = GCD(20, 30); System.out.println(result); void Methods 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 that defines a method named printgrade and invokes it to print the grade for a given score. void public static void main(string[] args) { 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) { 4
System.out.println('D'); else { System.out.println('F'); Passing Arguments by Values The arguments are passed by value to parameters when invoking a method. Consider the following code: Passing Arguments by Values public static void main(string[] args) { 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); 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. Overloaded Methods public static void main(string[] args) { Scanner input = new Scanner(System.in); int a = input.nextint(); int b = input.nextint(); int c = input.nextint(); 5
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(int a, int b, int c, int d) { return (a + b + c + d) / 4.0; Passing Arguments to the main Method The main method, like some other methods, takes arguments and returns nothing. You can pass arguments to it if you run your program from the console. Write your program using any text editor, like notepad++, and compile it using javac command, then run it using java command. Example: write a program that takes 5 words as arguments from the command line, then print each one using a JOPtionPane message. To accomplish this task, fellow the steps below: 1. Write the following code in a text editor, for example, notepad: Main.java import javax.swing.joptionpane; public class Main { public static void main(string[] args) { JOptionPane.showMessageDialog(null, args[0]); JOptionPane.showMessageDialog(null, args[1]); JOptionPane.showMessageDialog(null, args[2]); JOptionPane.showMessageDialog(null, args[3]); JOptionPane.showMessageDialog(null, args[4]); 6
2. Save your code in a file with the same name of the public class, and.java extension. For me, I will save it in D:\ drive. 3. Compile the previous file to convert the source code into byte code. Use javac filename.java command from the command line: Now you can notice a new file in the same folder: Main.class, which contains the compiled code: 7
4. Run the class file using java filename command and pass arguments to the program (to the main method). 5. Enjoy! ;) 8
Adding Java path to System Variables If you installed an earlier version of Java and tried to use javac command in the command line, you may face a problem like this: This is because that your system cannot locate where Java is installed. You just have to tell your system where to find javac tool, by adding the path of its folder to the environment variables. Like the following: 1. Go to the Java installation folder, by default it is: C:\Program Files\Java\jdkX.X.X_X\bin where X depend on the version of the installed java. I installed the latest version 1.8.0_20, so the folder path is C:\Program Files\Java\jdk1.8.0_20\bin 9
2. Copy the path of JDK bin folder: 3. Open environment variables. Right click on Computer and select Properties 10
4. Advanced system settings 11
5. Advanced >> Environment Variables: 12
6. Add new user variable with name Path and value of the Java bin folder path: 13
Alternatively, you can append the java path into Path variable in system variables. Separate two different paths with a semicolon (;). 14