L13-Methods

Views:
 
Category: Education
     
 

Presentation Description

JAVA Methods

Comments

Presentation Transcript

PowerPoint Presentation: 

December 15, 2011 ICS102 Lecture 13: Methods King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department

Outline: 

Outline Method definition Method structure Method invocation Method overloading

Introduction: 

Introduction The following code evaluates the function f(x, y): Write a program that reads three numbers x, y, z and finds the value of: int f, x, y; System.out.print(“Enter x and y: ”); x = k.nextInt(); y = k.nextInt(); if(x < y) f = x + y; else f = x*x + y*y; System.out.println(“f = “ + f);

Introduction: 

Introduction The code to evaluate the expression. int f1, f2, f3, x, y, z; System.out.print(“Enter x, y, z: ”); x = k.nextInt(); y = k.nextInt(); z = k.nextInt(); if(x < y) f1 = x + y; else f1 = x*x + y*y; if(x < z) f2 = x + z; else f2 = x*x + z*z; if(y < z) f3 = y + z; else f3 = y*y + z*z; System.out.println(“expression = “ + (f1 * f2) / f3); Same code but with different variables

Introduction: 

Introduction It is better to write the code once and use it as many times as needed with different variables. int f1, f2, f3, x, y, z; System.out.print(“Enter x, y, z: ”); x = k.nextInt(); y = k.nextInt(); z = k.nextInt(); f1 = f(x, y); f2 = f(x, z); f3 = f(y, z); System.out.println(“expression = “ + (f1 * f2) / f3); f(int a, int b){ if(a < b) result = a + b; else result = a*a + b*b; return result; } Use the code with a = x b = y Use the code again with a = x b = z Use the code again with a = y b = z What is the output if: x = 2 y = 4 z = 2

What is a method?: 

What is a method? A method is a collection of statements that does a certain task. General form: Where: type_returned : the type of value returned from this method at the end. It could be primitive type ( int , double ) or class type ( String ). name : any name can be given that follows rules of naming variables. param_list : list of values given to th e method. (method input) r eturn : return the value found by the method body. (method output) More on public and static modifiers will be discussed later. For now, any method should be public and static . public static type_returned name ( param_list ){ method_body return expression ; }

PowerPoint Presentation: 

What is a method? The method for evaluating the expression. Generally, any code must be in a method. A Java application program has a main method where the program starts execution. public static int f(int a, int b){ int result; if(a < b) result = a + b; else result = a*a + b*b; return result; }

PowerPoint Presentation: 

General Java Program class Prog{ public static void main(String []args){ ... meth ( argument_list ); ... } public static type_return meth ( param_list ){ ... return expression ; } } the main method where the program starts execution. Calling a method. Data given to the method is called argument. Argument values are copied to parameters The code executed until return Back to the call statement and continue execution remaining code in main

PowerPoint Presentation: 

Method Invocation import java.util.Scanner; class FirstMeth{ public static void main(String []args){ int f1, f2, f3, x, y, z; Scanner k = new Scanner(System.in); System.out.print(“Enter x, y, z: ”); x = k.nextInt(); y = k.nextInt(); z = k.nextInt(); f1 = f(x, y); f2 = f(x, z); f3 = f(y, z); System.out.println(“expression= “+(f1*f2)/f3); } public static int f(int a, int b){ int result; if(a < b) result = a + b; else result = a*a + b*b; return result; } } main x = y = z = f1 = f2 = f3 = f a = b = result = 2 4 2 2 4 6 6 2 8 8 4 2 20 20

Method Invocation: 

When a method is invoked: Arguments must match the parameters in type, order and number. Arguments of smaller size than parameters are automatically type cast. The value returned must match the type in the method heading. A return statement must be there if the method has a return type. Method Invocation public static double meth(int a, double b){ return a / b; } meth(2, 0.5) Valid call meth(2, “ICS”) Invalid call Second argument does not match second parameter in type meth(0.5, 2) Invalid call Order does not match meth(2, 0.5, 3) Invalid call The number of arguments is 3 and there are only 2 parameters meth(2, 2) Valid call 2 is automatically cast into double Expression type is double public static double meth(int a, double b){ double r = a / b; } Error No return statement inside the method

void Methods: 

void Methods A void method is a method that does not return any value. A void method does not require return statement but can be used to stop the method and go back to the calling statement. public static void showMenu(){ System.out.println(“1. Option 1”); System.out.println(“2. Option 2”); System.out.println(“3. Option 3”); System.out.println(“4. Exit”); } public static void showInitials(String fn, String ln){ if(fn.length() == 0 || ln.length() == 0){ System.out.println(“Incorrect name”); return; } System.out.println(fn.charAt(0) + ln.charAt(0)); }

Local Variables: 

Local Variables Parameters and any variables declared within a method definition is called a local variable. Local variables in different methods are independent. That means they can have the same name without any conflict. public static void main(String []args){ int a = 10, b = 20; avg(a, b); } public static void avg(int a, int b){ System.out.println((a + b)/2.0); }

Call-by-Value: 

Call-by-Value Parameters of primitive data types are called by value. Meaning a copy of the value is given to the parameters. Any changes done in the method does not affect the calling method. public static void main(String []args){ int a = 10; System.out.println(“a = “ + a); incrementBytwo(a); System.out.println(“a = “ + a); } public static void incrementBytwo(int a){ a = a + 2; System.out.println(“a = “ + a); } Both prints a = 10 prints a = 12

Call-by-reference (Array Parameters): 

Call-by-reference (Array Parameters) Parameters of class type or arrays are called by reference. The method will get a copy of the reference and therefore can affect the data in the calling method. public static void main(String []args){ int [] a = {1, 2, 3}; for(int i = 0; i < a.length; i++) System.out.println(a[i]+ “ “); incrementBytwo(a); for(int i = 0; i < a.length; i++) System.out.println(a[i]+ “ “); } public static void incrementBytwo(int [] b){ for(int i = 0; i < b.length; i++) b[i] = b[i] + 2; } a b 1 2 3 3 4 5

Method Overloading: 

Method Overloading The name of a method together with the number, order, and types of its parameters are called method signature. No two methods of the same class must have the same signature. if two methods have the same name but differ in the number or type of their parameters, then they are overloaded. Example: The compiler treats overloaded methods as completely different methods. It knows which one to call by using method signatures. String s = “Java”; s.substring(2); s.substring(0, 2);

Method Overloading: 

Method Overloading public static void main(String []args){ int a = 2, b = 5, c = -9; double d = 4.6, e = 1.4; System.out.println(add(a, b)); System.out.println(add(d, e)); System.out.println(add(a, b, c)); } public static int add(int x, int y){ return x + y; } public static double add(double x, double y){ return x + y; } public static int add(int x, int y, int z){ return x + y + z; }

Method Overloading: 

Method Overloading In overloading, the compiler will try to find an exact match between the call and the method signature without doing any type cast. public static void main(String []args){ int a = 2; double d = 4.6; System.out.println(increase(a)); System.out.println(increase(d)); } public static int increase(int x){ x += 2; return x; } public static double increase(double x){ x += 2; return x; }

Method Overloading: 

Method Overloading In case no exact match exist and more than one method (after type cast) can be used, an error will be produced. Even though this is a legal overloading, a bad call may produce an error. It is best to avoid overloading where there is a possible ambiguity with type cast. (a different name is a better option) The return type is not part of method signature. Overloading based on return type is not allowed. public static double add(int x, double y){ return x + y; } public static double add(double x, int y){ return x + y; } add(5, 10.0) Valid Use the first add method add(5.0, 10) Valid Use the second add method add(5, 10) Invalid Ambiguous. Cast 10 to double or 5??

Exercises: 

Exercises What is the output of the following program? public static void main(String []args){ int a = 10, b = 20; System.out.println(m1(a, 2)); b = m2(b / a); System.out.println(“a = “+ a + ”b = “ + b); } public static int m1(int a, int b){ a = 2 * m2(a); return a + b; } public static int m2(int a){ return a % 2; }

Exercises: 

Exercises What is the output? public static void main(String []args){ int [] a = {10, 20, 30}; if(m1(a)) m2(a, 0); else m2(a, 1); for(int i = 0; i < a.length; i++) System.out.println(a[i] + ” “); } public static boolean m1(int [] a){ return a[0] == a[1] / 2; } public static void m2(int [] a, int b){ a[b] = 1; }

Exercises: 

Exercises What is the output? public static void main(String []args){ int a = 5, b = 3; double c = 4.5, d = 6; System.out.println(sub(a, b)); System.out.println(sub(d, c)); System.out.println(sub(d, b*1.0)); } public static int sub(int x, int y){ y--; return x - y; } public static double sub(double x, double y){ return x - y; }

PowerPoint Presentation: 

The end Important to do at home : - read pages 206-212

Exercises: 

Exercises Write a method that takes as input an integer value and returns the sum of all integers less than that value. For example, if the input is 6, the output is 5+4+3+2+1 = 15. If the input is negative, the output should be -1. Write a method that takes as input an array of integers and returns the average of the values in the array.

Exercises: 

Exercises Write a method public void printTriangleNumbers(int n) such that: The call: printTriangleNumbers(5) prints the following on the screen: 1 2 3 4 5 1 2 3 4 1 2 3 1 2 1 The call: printTriangleNumbers(6) prints the following on the screen: 1 2 3 4 5 6 1 2 3 4 5 1 2 3 4 1 2 3 1 2 1 The call: printTriangleNumbers(3) prints the following on the screen: 1 2 3 1 2 1