CS110D: PROGRAMMING LANGUAGE I Computer Science department Lecture 7&8: Methods
Lecture Contents What is a method? Static methods Declaring and using methods Parameters Scope of declaration Overloading dr. Amal Khalifa,Fall14
Introduction Best way to develop and maintain a large program is to construct it from small, simple pieces, or modules. divide and conquer. dr. Amal Khalifa,Fall14
Modular Programming!! Methods help you modularize a program by separating its tasks into self-contained units. Written only once Hidden from other methods Can be reused : Use existing methods as building blocks to create new programs. dr. Amal Khalifa,Fall14
Methods A method: groups a sequence of statement takes input, performs actions, and produces output In Java, each method is defined within specific class
Tips!! dr. Amal Khalifa,Fall14
Java API Java programs combine new methods and classes that you write with predefined methods and classes available in the Java Application Programming Interface and in other class libraries. Class Math provides a collection of static methods enable you to perform common mathematical calculations. Method arguments may be constants, variables or expressions Defines common mathematical constants Math.PI (3.141592653589793) Math.E (2.718281828459045) dr. Amal Khalifa,Fall14
The Math methods
Example 1 Solve quadratic equation ax 2 + bx + c = 0. public class Quadratic { public static void main(string[] args) { double a,b,c,d; // input coefficient values.. } } // calculate roots d = Math.sqrt(b*b - 4.0*a*c); double root1 = (-b + d) / (2.0*a); double root2 = (-b - d) / (2.0*a); // print them out System.out.println(root1); System.out.println(root2); Dr. Amal Khalifa, 2012
Example2: Simulation- Flipping a coin 10 public class Flip { public static void main(string[] args) { for (int i=0; i<1000; i++) if (Math.random() < 0.5) System.out.println("Heads"); else System.out.println("Tails"); } } % java Flip Heads can produce only double values in the range of 0.0 and 1.0. % java Flip Heads % java Flip Tails Dr. Amal Khalifa, 2014
The Math Class dr. Amal Khalifa,Fall14
Tip!! dr. Amal Khalifa,Fall14
User defined methods declare Call test Reuse dr. Amal Khalifa,Fall14
Method Declaration: Header A method declaration begins with a method header public class MyClass { static int min ( int num1, int num2 ) properties return type method name parameter list The parameter list specifies the type and name of each parameter The name of a parameter in the method declaration is called a formal argument
Method Declaration: Body The header is followed by the method body: class MyClass { static int min(int num1, int num2) { int minvalue = (num1 < num2)? num1 : num2; return minvalue; } } Computer Science Department
The return Statement The return type of a method indicates the type of value that the method sends back to the calling location The return statement specifies the value that will be returned Its expression must conform to the return type A method can return at most 1 value A method that does not return a value has a void return type Computer Science Department
Be careful!! dr. Amal Khalifa,Fall14
Calling a Method Each time a method is called, the values of the actual arguments in the invocation are assigned to the formal arguments int num = min(2, 3); static int min (int num1, int num2) { } int minvalue = (num1 < num2? num1 : num2); return minvalue; Computer Science Department
Example Method call
Example Method declaration static return
Run!!
Example: void methods 22 Write a function that outputs the multiplication table of a given number.
Method calling A method can call another method, who can call another method, main min(num1, num2, num3) println() min(1, 2, 3); println( ) dr. Amal Khalifa,Fall14
Method Call Stack Stack: data structure Analogous to a pile of dishes A dish is placed on the pile at the top (referred to as pushing the dish onto the stack). A dish is removed from the pile from the top (referred to as popping the dish off the stack). Last-in, first-out (LIFO) data structures The last item pushed (inserted) on the stack is the first item popped (removed) from the stack. dr. Amal Khalifa,Fall14
LIFO behavior: 25 the caller pushes the return address onto the stack, when it finishes, the called function pops the return address off the call stack Control is transfers to that address. memory is finite --> stack overflow may occurs
Argument Promotion and Casting Argument promotion Converting an argument s value, if possible, to the type that the method expects to receive in its corresponding parameter. Conversions may lead to compilation errors if Java s promotion rules are not satisfied. Promotion rules specify which conversions are allowed. apply to expressions containing values of two or more primitive types and to primitive-type values passed as arguments to methods. Each value is promoted to the highest type in the expression.
Argument casting In cases where information may be lost due to conversion, the Java compiler requires you to use a cast operator to explicitly force the conversion to occur otherwise a compilation error occurs.
Be careful!!
Scope of Declarations Declarations introduce names that can be used to refer to such Java entities. The scope of a declaration is the portion of the program that can refer to the declared entity by its name. Such an entity is said to be in scope for that portion of the program. If a local variable or parameter in a method has the same name as a field of the class, the field is hidden until the block terminates execution this is called shadowing. dr. Amal Khalifa,Fall14
Scope Rules 30 Global: Declared "outside" function body final double TAXRATE = 0.05; final double PI = 3.14159; Local: Declared inside" a function or block * Declared inside body of given function or block of code * Available only within that function * Can we have variables with same names declared in different method?? Dr. Hamad, Dr. Khalifa
Example
Method Overloading Methods of the same name declared in the same class Must have different sets of parameters (signatures). the compiler differentiates signatures by : the number of parameters, the types of the parameters and the order of the parameter types in each signature. Method calls cannot be distinguished by return type. Overloaded methods can have different return types if the methods have different parameter lists. Overloaded methods need not have the same number of parameters.
Example Same name different tasks matching by signature Literal floating-point values are treated as type double
Be careful!!
That s all [1] 6.1 6.7, 6.11, 6.12 dr. Amal Khalifa,Fall14