在按值传递参数时需要传递参数。它们的顺序应与方法规范中的参数顺序相同。参数可以通过值或引用传递。
通过值传递参数是使用参数调用方法。 通过这样将参数值将传递给参数。
示例
以下程序显示了按值传递参数的示例。 即使在方法调用之后,参数的值仍保持不变。
public class swappingExample {
public static void main(String[] args) {
int a = 30;
int b = 45;
System.out.println("Before swapping, a = " + a + " and b = " + b);
// 调用交换方法
swapFunction(a, b);
System.out.println("Now, Before and After swapping values will be same here:");
System.out.println("After swapping, a = " + a + " and b is " + b);
}
public static void swapFunction(int a, int b) {
System.out.println("Before swapping(Inside), a = " + a + " b = " + b);
// 交换 n1 和 n2
int c = a;
a = b;
b = c;
System.out.println("After swapping(Inside), a = " + a + " b = " + b);
}
}
执行上面示例代码,得到以下结果:
Before swapping, a = 30 and b = 45
Before swapping(Inside), a = 30 b = 45
After swapping(Inside), a = 45 b = 30
Now, Before and After swapping values will be same here:
After swapping, a = 30 and b is 45
当一个类有两个或多个同名但方法不同参数的方法时,称为方法重载。 它与重写不同。 在重写中,方法具有相同的方法名称,类型,参数数量等。
在前面讨论的用于查找最小整数类型数的示例中,假设想要查找两个double类型的最小数值。 可引入重载的概念以创建具有相同名称但不同参数的两个或更多方法。
参考以下示例代码 -
public class ExampleOverloading {
public static void main(String[] args) {
int a = 11;
int b = 6;
double c = 7.3;
double d = 9.4;
int result1 = getMin(a, b);
// 具有相同函数名称,但数字不同参数
double result2 = getMin(c, d);
System.out.println("Minimum Value = " + result1);
System.out.println("Minimum Value = " + result2);
}
// 处理 int 类型的数值(方法重载)
public static int getMin(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
// 处理 double 类型的数值(方法重载)
public static double getMin(double n1, double n2) {
double min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
}
执行上面示例代码,得到以下结果:
Minimum Value = 6
Minimum Value = 7.3
重载方法使程序可读。这里,两个方法由相同的名称给出但具有不同的参数类型。结果是求int类型和double类型的最小数。
有时希望在运行程序时将一些信息传递给程序。它是通过将命令行参数传递给main()来实现的。
命令行参数是执行时在命令行上直接跟随程序名称的信息。 要访问Java程序中的命令行参数非常简单。 它们作为字符串存储在传递给main()的String类型数组中。
示例
以下程序显示传递给程序的所有命令行参数 -
public class CommandLine {
public static void main(String args[]) {
for(int i = 0; i<args.length; i++) {
System.out.println("args[" + i + "]: " + args[i]);
}
}
}
使用以下方式执行此程序 -
C:/> java CommandLine this is a command line 200 -100
那么将得到以下结果:
args[0]: this
args[1]: is
args[2]: a
args[3]: command
args[4]: line
args[5]: 200
args[6]: -100