CS110D: PROGRAMMING LANGUAGE I · PDF fileto such Java entities. The scope of a declaration is...
Transcript of CS110D: PROGRAMMING LANGUAGE I · PDF fileto such Java entities. The scope of a declaration is...
CS110D: PROGRAMMING
LANGUAGE I
Lecture 7&8: Methods Computer Science
department
Lecture Contents
dr. Amal Khalifa,Fall14
What is a method?
Static methods
Declaring and using methods
Parameters
Scope of declaration
Overloading
Introduction
dr. Amal Khalifa,Fall14
Best way to develop and maintain a large program
is to construct it from small, simple pieces, or
modules.
divide and conquer.
Modular Programming!!
dr. Amal Khalifa,Fall14
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.
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
dr. Amal Khalifa,Fall14
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)
The Math methods
Example 1
Solve quadratic equation ax2 + 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
can produce only double values in the
range of 0.0 and 1.0.
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
% java Flip
Heads
% java Flip
Tails
Dr. Amal Khalifa, 2014
10
The Math Class
dr. Amal Khalifa,Fall14
Tip!!
dr. Amal Khalifa,Fall14
User defined methods
dr. Amal Khalifa,Fall14
declare
Call
test
Reuse
Method Declaration: Header
A method declaration begins with a method header
method
name
return
type
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
public class MyClass
{
static int min ( int num1, int num2 ) …
properties
Method Declaration: Body
The header is followed by the method body:
static int min(int num1, int num2)
{
int minValue = (num1 < num2) ? num1 : num2;
return minValue;
}
class MyClass
{ …
…
}
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
static int min (int num1, int num2)
{
int minValue = (num1 < num2 ? num1 : num2);
return minValue;
}
int num = min(2, 3);
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
dr. Amal Khalifa,Fall14
A method can call another method, who can call
another method, …
min(num1, num2, num3)
println()
…println(…)
min(1, 2, 3);
main
Method Call Stack
dr. Amal Khalifa,Fall14
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.
LIFO behavior:
• 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
25
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
dr. Amal Khalifa,Fall14
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.
Scope Rules…
Dr. Hamad, Dr. Khalifa
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??
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!!
[1] 6.1 6.7, 6.11, 6.12
That’s all …
dr. Amal Khalifa,Fall14