Java Reference
In-Depth Information
The arguments are passed by value to parameters when invoking a method.
Key
Point
The power of a method is its ability to work with parameters. You can use
println
to print
any string and
max
to find the maximum of any two
int
values. When calling a method, you
need to provide arguments, which must be given in the same order as their respective parame-
ters in the method signature. This is known as
parameter order association.
For example, the
following method prints a message
n
times:
parameter order association
public static void
nPrintln(String message,
int
n) {
for
(
int
i =
0
; i < n; i++)
System.out.println(message);
}
You can use
nPrintln("Hello", 3)
to print
Hello
three times. The
nPrintln("Hello",
3)
statement passes the actual string parameter
Hello
to the parameter
message
, passes
3
to
n
,
and prints
Hello
three times. However, the statement
nPrintln(3, "Hello")
would be
wrong. The data type of
3
does not match the data type for the first parameter,
message
, nor
does the second argument,
Hello
, match the second parameter,
n
.
Caution
The arguments must match the parameters in
order, number,
and
compatible type,
as
defined in the method signature. Compatible type means that you can pass an argument
to a parameter without explicit casting, such as passing an
int
value argument to a
double
value parameter.
When you invoke a method with an argument, the value of the argument is passed to the para-
meter. This is referred to as
pass-by-value.
If the argument is a variable rather than a literal
value, the value of the variable is passed to the parameter. The variable is not affected, regard-
less of the changes made to the parameter inside the method. As shown in Listing 5.4, the
value of
x
(
1
) is passed to the parameter
n
to invoke the
increment
method (line 5). The
parameter
n
is incremented by
1
in the method (line 10), but
x
is not changed no matter what
the method does.
pass-by-value
L
ISTING
5.4
Increment.java
1
public class
Increment {
2
public static void
main(String[] args) {
3
int
x =
1
;
4 System.out.println(
"Before the call, x is "
+ x);
5
6 System.out.println(
"After the call, x is "
+ x);
7 }
8
9
invoke increment
increment(x);
public static void
increment(
int
n) {
n++;
increment
n
10
11 System.out.println(
"n inside the method is "
+ n);
12 }
13 }
Before the call, x is 1
n inside the method is 2?
After the call, x is 1