0% found this document useful (0 votes)
11 views

Unit 2 - Methods

The document discusses methods in Java. It defines methods as collections of statements grouped together to perform tasks or operations. It outlines the goals of introducing key concepts about methods such as defining methods, invoking methods with parameters, determining scope of local variables, and passing arguments by value. It also covers method overloading. The document explains different components of a method such as the method header, body, parameters, return type, and calling methods.

Uploaded by

Leon Chong
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Unit 2 - Methods

The document discusses methods in Java. It defines methods as collections of statements grouped together to perform tasks or operations. It outlines the goals of introducing key concepts about methods such as defining methods, invoking methods with parameters, determining scope of local variables, and passing arguments by value. It also covers method overloading. The document explains different components of a method such as the method header, body, parameters, return type, and calling methods.

Uploaded by

Leon Chong
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

Unit 2: Methods

Unit 2 Goals

• To introduce the concepts of methods


• To define methods
• To invoke methods with actual parameters
• To determine the scope of local variables
• To pass arguments by value
• To use method overloading and understand ambiguous
overloading
• To introduce Java Math class

2
Method

• A method is a collection of statements that are grouped together to


perform an operation or a task.

• You can think of the method body as a black box that contains the
detailed implementation for the method.

• Methods can be used to reduce redundant coding and enable code


reuse. Methods can also be used to modularize code and improve
the quality of the program.

public static int max(int a, int b) Optional arguments Optional return


{ for Input value
if(a > b)
return a; Method Header
else Black
return b; Method body
Box
}

3
Method

Types of Java methods


Depending on whether a method is defined by the
user, or available in the standard library, there are
two types of methods in Java:

• Standard Library Methods - The standard library


methods are built-in methods in Java that are
readily available for use.

• User-defined Methods - methods of our own


choice to perform some task.

4
Method declaration

Method Return Method


Modifiers Type Name Parameters

public static int max(int n1, int n2)


{
…;
}

5
Method Signature

Method signature is the combination of the method name and the


parameter list.

Define a method Invoke a method

return value method formal


modifier type name parameters
int z = max(x, y);
method
public static int max(int num1, int num2) {
header
actual parameters
int result; (arguments)
method
body parameter list
if (num1 > num2)
result = num1;
else
method
result = num2; signature

return result; return value


}

6
Formal Parameters

The variables defined in the method header are known as formal


parameters.

Define a method Invoke a method

return value method formal


modifier type name parameters
int z = max(x, y);
method
public static int max(int num1, int num2) {
header
actual parameters
int result; (arguments)
method
body parameter list
if (num1 > num2)
result = num1;
else
method
result = num2; signature

return result; return value


}

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.

Define a method Invoke a method

return value method formal


modifier type name parameters
int z = max(x, y);
method
public static int max(int num1, int num2) {
header
actual parameters
int result; (arguments)
method
body parameter list
if (num1 > num2)
result = num1;
else
method
result = num2; signature

return result; return value


}

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.

Define a method Invoke a method

return value method formal


modifier type name parameters
int z = max(x, y);
method
public static int max(int num1, int num2) {
header
actual parameters
int result; (arguments)
method
body parameter list
if (num1 > num2)
result = num1;
else
method
result = num2; signature

return result; return value


}

9
Return Value Type from Method

• A void method is one that simply performs a task and


then terminates.
System.out.println("Hi!");

• A value-returning method not only performs a task, but


also sends a value back to the code that called it.

int number = Integer.parseInt("700");

10
Calling Methods

pass the value of i


pass the value of j

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


the max method the max method
result: result: 5
num2: 2 num2: 2
num1: 5 num1: 5

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

• A return statement is required for a value-returning method.


• The method shown below is logically correct, but it has a compilation
error because the Java compiler thinks it possible that this method
does not return any value.

public static int sign(int n) { public static int sign(int n) {


if (n > 0) if (n > 0)
return 1; return 1;
else if (n == 0) else if (n == 0)
return 0; return 0;
else if (n < 0) else
return –1; return –1;
} }

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

public Student(String na) { // constructor


name = na; instance (non-static)
} method
public String getName() {
return name;
}
class (static)
public static String schoolName() {
method
return "UTAR";
}

public class TestAppication{

public static void main(String[] args) {


Student s1 = new Student("Alex"); object.method()
System.out.println(s1.getName());

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.

public class Test


{
public static void main(String[] args)
{
int a = 10, b =2 0;
int c = max(a,b); // Test.max(a,b);
System.out.println(c);
}

public static int max(int a, int b)


{
if(a>b)
return a;
else
return b;
}
}

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.

public static void method1() {


.
.
for (int i = 1; i < 10; i++) {
.
The scope of i .
int j;
.
The scope of j .
.
}
}

19
Scope of Local Variables

It is fine to declare i in two It is wrong to declare i in


non-nesting blocks two nesting blocks

public static void method1() { public static void method2() {


int x = 1;
int y = 1; int i = 1;
int sum = 0;
for (int i = 1; i < 10; i++) {
x += i; for (int i = 1; i < 10; i++) {
} sum += i;
}
for (int i = 1; i < 10; i++) {
y += i; }
}
}

OK Error

20
Passing Arguments

• When you call a method, the arguments you send to a


method must match in order – both in number and in
type.

• The following program shows a class containing a three


argument method and a main() that calls it twice, once
using variable arguments and again using constant
arguments.

21
ComputeCommission.java

public class ComputeCommission


{
public static void main (String[] args)
{
char vType = 'A';
int value = 10000;
double commissionRate = 0.05;
computeCommission(value, commissionRate, vType);
computeCommission(30000, 0.03, 'B'); // constants arguments
}

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

• In Java, all arguments of the primitive data types are passed


by value, which means that only a copy of an argument’s
value is passed into a parameter variable.

• If a parameter variable is changed inside a method, it has no


effect on the original argument.
• Argument: a data value that is passed to a method for its processing
pass the value of i
pass the value of j

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.
*/

public class PassByValue


{
public static void main(String[] args)
{
int number = 99; // number starts with 99

// Display the value in number.


System.out.println("number is " + number);

// Call changeMe, passing the value in number


// as an argument.
changeMe(number);

// Display the value in number again.


System.out.println("number is " + number);
}

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.");

// Change the myValue parameter variable to 0.


myValue = 0;

// Display the value in myValue.


System.out.println("Now the value is " + myValue);
}
}

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.

• Overloading is a feature that allows a class to have more than one


method having the same name, if their argument lists are different.

• Advantage of method overloading


Method overloading increases the readability of the program.

Different ways to overload the method


There are two ways to overload the method in java

- By changing number of arguments


static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}

- By changing the data type


static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
26
Overloading Methods
• Overloading methods example

/** Return the max of two int values */


public static int max(int num1, int num2) {
if (num1 > num2)
return num1;
else
return num2;
}

/** Find the max of two double values */


public static double max(double num1, double num2) {
if (num1 > num2)
return num1;
else
return num2;
}

/** Return the max of three double values */


public static double max(double num1, double num2, double num3) {
return max(max(num1, num2), num3);
}
27
Overloading Methods cont.

// Invoke the max method with int parameters


System.out.println( max(3, 4) );

// Invoke the max method with the double parameters


System.out.println( max(3.0, 4.1) );

// Invoke the max method with three double parameters


System.out.println( max(3.0, 4.0, 5.0) );

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

public class AmbiguousOverloading {


public static void main(String[] args) {
System.out.println(max(1, 2));
Compiler error !
}

public static double max(int num1, double num2) {


if (num1 > num2)
return num1;
else
return num2;
}

public static double max(double num1, int num2) {


if (num1 > num2)
return num1;
else
return num2;
}
}

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:

• cos(double a) Math.sin(0) returns 0.0


• tan(double a) Math.sin(Math.PI / 6)
returns 0.5
• acos(double a) Math.sin(Math.PI / 2)
returns 1.0
• asin(double a)
Math.cos(0) returns 1.0
• atan(double a) Math.cos(Math.PI / 6)
returns 0.866
Math.cos(Math.PI / 2)
Radians returns 0
Math.toRadians(90)

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:

Returns a random integer


(int)(Math.random() * 10)
between 0 and 9.

50 + (int)(Math.random() * 50) Returns a random integer


between 50 and 99.

In general,

a + Math.random() * b Returns a random number between


a and a + b, excluding a + b.

37

You might also like