Download Methods in Java Programming: Lecture Notes for Computer Programming 1 and more Exercises Programming Languages in PDF only on Docsity!
١
Chapter 5 Methods
Lecture notes for computer programming 1 Lecture notes for computer programming 1
Faculty of Engineering and Information Technology^ Faculty of Engineering and Information Technology
Prepared by:Prepared by:
IyadIyad
AlbayoukAlbayouk
٢
Introducing Methods
A method is a collection of statements that aregrouped together to perform an operation.
public static int max(int num1, int num2) {
int result;if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
modifier
return value type
method name
formal parameters
return value
methodheader methodbody
parameter list
Define a method
Invoke a method
int z = max(x, y);
actual parameters
(arguments)
٤
Introducing Methods, cont.
A method may return a value. ThereturnValueType
is the data type of the value the
method returns. If the method does not return avalue, the returnValueType
is the keyword void
For example, the returnValueType
in the main
method is void
٥
Calling Methods This program demonstrates calling a method max to return thelargest of the
int
values
public class TestMax {/** Main method */
public static void main(String[] args) {
int
i = 5;
int
j = 2;
int k = max(i, j);
System.out.println("The maximum between " + i +
" and " + j +
" is " + k); }
/** Return the max between two numbers */public static int max(int num1, int num2) {
int result;if (num1 > num2)
result = num1;
else
result = num2;
return result;
٧
CAUTION A return statement is required for a nonvoidmethod. The following method is logicallycorrect, but it has a compilation error,because the Java compiler thinks it possiblethat this method does not return any value.
public
static
public
static
intint
sign(intsign(int
n) {n) {
if (n > 0)
return
if (n > 0)
return
else
if (n
== 0) return 0;
else
if (n
== 0) return 0;
else
if (n
< 0) return
else
if (n
< 0) return
To fix this problem, delete if (n<0) in the code.
٨
Reuse Methods from OtherClasses
NOTE: One of the benefits of methods is for reuse. Themax
method can be invoked from any class besides
TestMax
. If you create a new class Test
, you can invoke
the max
method using ClassName.methodName
(e.g.,
TestMax.max
١٠
Passing Parameters
public
static
void
public
static
void
nPrintln(StringnPrintln(String
message,message,
intint
n)n)
{^ {
for
(
for
(
intint
i
=
0;
i
<
n;
i++)
i
=
0;
i
<
n;
i++)
System.out.println(message System.out.println(message
););
}^ }
Suppose you invoke the method using
nPrintln(“Welcome to Java”
What is the output?Suppose you invoke the method using
nPrintln(“Computer Science”
What is the output?
١١
Pass by Value
This program demonstrates passing values to the methods.
public class TestPassByValue {public static void main(String[] args) {
int
num1 = 1;
int
num2 = 2;
System.out.println("Before invoking the swap method, num1 is " +
num1 + " and num2 is " + num2); swap(num1, num2); System.out.println("After invoking the swap method, num1 is " + num1 + " and num2 is " + num2); } public static void swap(int n1, int n2) {
System.out.println("\tInside the swap method");System.out.println("\t\tBefore
swapping n1 is " + n
+ " n2 is " + n2);
int
temp = n1;
n1 = n2;n2 = temp; System.out.println("\t\tAfter
swapping n1 is " + n
+ " n2 is " + n2);
١٣
Overloading Methods
Example of overloading the
maxmax
Method
public class TestMethodOverloading {
public static void main(String[] args) {
System.out.println("The maximum between 3 and 4 is “
+ max(3, 4)); System.out.println("The maximum between 3.0 and 5.4 is “
+ max(3.0, 5.4)); System.out.println("The maximum between 3.0, 5.4, and 10.14 is “
+ max(3.0, 5.4, 10.14));
} public static int max(int num1, int num2) {
if (num1 > num2)
return num1; else
return num2; }
public static double max(double num1, double num2) {
if (num1 > num2)
return num1; else
return num2; }
public static double max(double num1, double num2, double num3) {
return max(max(num1, num2), num3); }}
١٤
Ambiguous Invocation
Sometimes there may be two or more^ Sometimes there may be two or morepossible matches for an invocation of a^ possible matches for an invocation of amethod, but the compiler cannot determine^ method, but the compiler cannot determinethe most specific match. This is referred to^ the most specific match. This is referred toas^ as
ambiguous invocationambiguous invocation
. Ambiguous. Ambiguous
invocation is a compilation error.^ invocation is a compilation error.
١٦
Scope of Local Variables
A local variable: a variable defined inside amethod.
Scope: the part of the program where thevariable can be referenced.
The scope of a local variable starts from itsdeclaration and continues to the end of theblock that contains the variable. A localvariable must be declared before it can beused.
١٧
Scope of Local Variables, cont.
You can declare a local variable with the samename multiple times in different non-nestingblocks in a method, but you cannot declare alocal variable twice in nested blocks.
١٩
Scope of Local Variables, cont.
public static void method1() {
int x = 1; int y = 1; for (
int i
= 1; i < 10; i++) {
x += i;
} for (
int i
= 1; i < 10; i++) {
y += i;
}
It is fine to declare i in two non-nesting blocks }
public static void method2() {
int i
= 1;
int sum = 0; for (
int i
= 1; i < 10; i++) {
sum += i;
}
}
It is wrong to declare i
in
two nesting blocks
٢٠
Method Abstraction You can think of the method body as a blackbox that contains the detailedimplementation for the method.
Method Signature
Method body
Black Box
Optional arguments
for Input
Optional return
value