Java Reference
In-Depth Information
Methods can be used to define reusable code and organize and simplify coding.
Key
Point
Suppose that you need to find the sum of integers from
1
to
10
, from
20
to
37
, and from
35
to
49
, respectively. You may write the code as follows:
problem
int
sum =
0
;
for
(
int
i =
1
; i <=
10
; i++)
sum += i;
System.out.println(
"Sum from 1 to 10 is "
+ sum);
sum =
0
;
for
(
int
i =
20
; i <=
37
; i++)
sum += i;
System.out.println(
"Sum from 20 to 37 is "
+ sum);
sum =
0
;
for
(
int
i =
35
; i <=
49
; i++)
sum += i;
System.out.println(
"Sum from 35 to 49 is "
+ sum);
You may have observed that computing these sums from
1
to
10
, from
20
to
37
, and from
35
to
49
are very similar except that the starting and ending integers are different. Wouldn't
it be nice if we could write the common code once and reuse it? We can do so by defining a
method and invoking it.
The preceding code can be simplified as follows:
why methods?
1
public static int
sum(
int
i1,
int
i2) {
2
int
result =
0
;
3
for
(
int
i = i1; i <= i2; i++)
4 result += i;
5
6
define
sum
method
return
result;
7 }
8
9
public static void
main(String[] args) {
10 System.out.println(
"Sum from 1 to 10 is "
+ sum(
1
,
10
));
11 System.out.println(
"Sum from 20 to 37 is "
+ sum(
20
,
37
));
12 System.out.println(
"Sum from 35 to 49 is "
+ sum(
35
,
49
));
13 }
main
method
invoke
sum
Lines 1-7 define the method named
sum
with two parameters
i1
and
i2
. The statements in
the
main
method invoke
sum(1, 10)
to compute the sum from
1
to
10
,
sum(20, 37)
to
compute the sum from
20
to
37
, and
sum(35, 49)
to compute the sum from
35
to
49
.
A
method
is a collection of statements grouped together to perform an operation. In earlier chap-
ters you have used predefined methods such as
System.out.println
,
System.exit
,
Math
.pow
, and
Math.random
. These methods are defined in the Java library. In this chapter, you will
learn how to define your own methods and apply method abstraction to solve complex problems.
method
A method definition consists of its method name, parameters, return value type, and body.
Key
Point
The syntax for defining a method is as follows:
modifier returnValueType methodName(list of parameters) {
// Method body;
}
Search WWH ::
Custom Search