调用一个方法时候需要提供参数,你必须按照参数列表指定的顺序提供。
例如,下面的方法连续n次打印一个消息:
public static void nPrintln(String message, int n) {
for (int i = 0; i < n; i++)
System.out.println(message);
}
示例
下面的例子演示按值传递的'效果。
该程序创建一个方法,该方法用于交换两个变量。
public class TestPassByValue {
public static void main(String[] args) {
int num1 = 1;
int num2 = 2;
System.out.println("Before swap method, num1 is " +
num1 + " and num2 is " + num2);
// 调用swap方法
swap(num1, num2);
System.out.println("After 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 " + n1
+ " n2 is " + n2);
// 交换 n1 与 n2的值
int temp = n1;
n1 = n2;
n2 = temp;
System.out.println("\t\tAfter swapping n1 is " + n1
+ " n2 is " + n2);
}
}
以上实例编译运行结果如下:
Before swap method, num1 is 1 and num2 is 2
Inside the swap method
Before swapping n1 is 1 n2 is 2
After swapping n1 is 2 n2 is 1
After swap method, num1 is 1 and num2 is 2
传递两个参数调用swap方法。有趣的是,方法被调用后,实参的值并没有改变。
1.
2.
3.
4.
5.
6.
7.
8.
9.