Unit 2 - Methods
Unit 2 - Methods
Unit 2 Goals
2
Method
• You can think of the method body as a black box that contains the
detailed implementation for the method.
3
Method
4
Method declaration
5
Method Signature
6
Formal Parameters
7
Actual Parameters
When a method is invoked, you pass a value to the parameter. This value is
referred to as actual parameter or argument.
8
Return Value Type from Method
A method may return a value. The returnValueType is the data type of the value
the method returns.
If the method does not return a value, the returnValueType is the keyword void.
For example, the returnValueType in the main method is void.
9
Return Value Type from Method
10
Calling Methods
public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}
11
Call Stacks
(b)
public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
(a)
int k = max(i, j); if (num1 > num2)
(d) result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result; (c)
(e) }
Space required for Space required for Space required for Space required for
the main method the main method the main method the main method
k: k: k: k: 5 Stack is empty
j: 2 j: 2 j: 2 j: 2
i: 5 i: 5 i: 5 i: 5
(a) The main (b) The max (c) The max method (d) The max method is (e) The main
method is invoked. method is invoked. is being executed. finished and the return method is finished.
value is sent to k.
12
CAUTION on Method Return
Compile error!
This method must return a result of type int
To fix this problem, delete if (n < 0) , so that the compiler will see a return
statement to be reached regardless of how the if statement is evaluated.
13
Method Call Syntax in Java
• Java is fully object-oriented, calling a method must go through
a class (class method) or an object (instance method).
ClassName.methodName(parameters) if the method is a
static method
OR
ClassName.objectName.methodName(parameters) if object
is a public static object
OR
objectName.methodName(parameters) if instance method
Example:
System.out.println("Hello, Dave!");
System – Class name, out – Object Name, println –
method name.
14
Method Call Syntax in Java - Example
public class Student {
private String name; // data field
System.out.println(Student.schoolName());
}
} Class.method()
15
Method Call Syntax in Java
• We may call a method directly if it is within the same class.
16
Scope of Local Variables
• A local variable: a variable defined inside a method.
(A variable defined in a class is called Data field/Data member)
• Scope: the part of the program where the variable can be
referenced.
• 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 before it can be used.
void myMethod()
{
...
int localVal = 3;
...
Scope localVal += 5;
17
Scope of Local Variables
• You can declare a local variable with the same name
multiple times in different non-nesting blocks in a method,
• but you cannot declare a local variable twice in nested
blocks.
void myMethod()
{
{
int localVal = 3;
...
}
{
int localVal = 5; // OK
{
double localVal = 8; // NOT OK
}
}
}
18
Scope of Local Variables
• A variable declared in the initial action part of a for loop
header has its scope in the entire loop.
• But a variable declared inside a for loop body has its scope
limited in the loop body from its declaration and to the end of
the block that contains the variable.
19
Scope of Local Variables
OK Error
20
Passing Arguments
21
ComputeCommission.java
public static void computeCommission (int value, double rate, char vehicle)
{
double commission;
commission = value * rate;
System.out.println("\nThe " + vehicle + " type vehicle is worth $" + value);
System.out.println("with " + (rate * 100) + "% commission rate, the commission
is $" + commission);
}
}
22
Pass by Value
public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}
23
PassByValue.java
/**
This program demonstrates that only a copy of an argument
is passed into a method.
*/
24
PassByValue.java
/**
The changeMe method accepts an argument and then
changes the value of the parameter.
*/
public static void changeMe(int myValue)
{
System.out.println("I am changing the value.");
number is 99
I am changing the value.
Now the value is 0
number is 99
25
Overloading Methods
• Overloading methods enables you to define the methods with the same
name as long as their signatures are different.
28
Ambiguous Invocation
• When you overload methods, you risk creating an
ambiguous situation - one which the compiler cannot
determine which method to use.
29
Ambiguous Invocation
30
Java Math Class
The Math Class
• Class constants:
– PI // 3.1415926..
–E // 2.71828..
• Class methods:
– Trigonometric Methods
– Exponent Methods
– Rounding Methods
– min, max, abs, and random Methods
32
Trigonometric Methods
• sin(double a) Examples:
33
Exponent Methods
• exp(double a) Examples:
Returns e raised to the power of a.
• log(double a) Math.exp(1) returns 2.71
Returns the natural logarithm of a. Math.log(2.71) returns 1.0
• log10(double a) Math.pow(2, 3) returns 8.0
Returns the 10-based logarithm of Math.pow(3, 2) returns 9.0
a. Math.pow(3.5, 2.5) returns
22.91765
• pow(double a, double b)
Math.sqrt(4) returns 2.0
Returns a raised to the power of b.
Math.sqrt(10.5) returns 3.24
• sqrt(double a)
Returns the square root of a.
34
Rounding Methods
• double ceil(double x)
x rounded up to its nearest integer. This integer is returned as a
double value.
• double floor(double x)
x is rounded down to its nearest integer. This integer is returned
as a double value.
• double rint(double x)
x is rounded to its nearest integer. If x is equally close to two
integers, the even one is returned as a double.
• int round(float x)
Return (int)Math.floor(x+0.5).
• long round(double x)
Return (long)Math.floor(x+0.5).
35
min, max, and abs
• max(a, b)and min(a, b) Examples:
Returns the maximum or
minimum of two parameters. Math.max(2, 3) returns 3
• abs(a) Math.max(2.5, 3) returns
Returns the absolute value of the 3.0
parameter. Math.min(2.5, 3.6) returns
• random() 2.5
Returns a random double value Math.abs(-2) returns 2
in the range [0.0, 1.0). Math.abs(-2.1) returns 2.1
36
The random Method
Generates a random double value greater than or equal to 0.0
and less than 1.0 (0 <= Math.random() < 1.0).
Examples:
In general,
37