Java 方法参数

Parameters 与 Arguments

信息可以作为 Parameters 参数传递给方法。Parameters 在方法中充当变量。

Parameters 参数在方法名称后的括号内指定。可以添加任意数量的参数,只需用逗号分隔即可。下面的示例有一个方法,该方法将名为 fnameString 字符串作为参数。调用该方法时,我们传递一个名字,该名字在方法内部用于打印全名:

实例
  1. public class Main {
  2. static void myMethod(String fname) {
  3. System.out.println(fname + " Refsnes");
  4. }
  5. public static void main(String[] args) {
  6. myMethod("Liam");
  7. myMethod("Jenny");
  8. myMethod("Anja");
  9. }
  10. }

当一个 parameter 参数被传递给该方法时,它被称为 argument(方法内的参数)。从上面的例子来看:fname 是一个参数,而 LiamJennyAnja 是参数。


多个参数

可以有任意多个参数:

实例
  1. public class Main {
  2. static void myMethod(String fname, int age) {
  3. System.out.println(fname + " is " + age);
  4. }
  5. public static void main(String[] args) {
  6. myMethod("Liam", 5);
  7. myMethod("Jenny", 8);
  8. myMethod("Anja", 31);
  9. }
  10. }
请注意,当使用多个参数时,方法调用的参数数必须与参数数相同,并且参数的传递顺序必须相同。

返回值

上面示例中使用的 void 关键字表示该方法不应返回值。如果希望方法返回值,可以使用基本数据类型(如 intchar 等)而不是 void,并在方法内部使用 return 关键字将值返回:

实例
  1. public class Main {
  2. static int myMethod(int x) {
  3. return 5 + x;
  4. }
  5. public static void main(String[] args) {
  6. System.out.println(myMethod(3));
  7. }
  8. }

本例返回一个方法的两个 parameters 参数之和:

实例
  1. public class Main {
  2. static int myMethod(int x, int y) {
  3. return x + y;
  4. }
  5. public static void main(String[] args) {
  6. System.out.println(myMethod(5, 3));
  7. }
  8. }

还可以将结果存储在变量中(推荐使用,因为它更易于读取和维护):

实例
  1. public class Main {
  2. static int myMethod(int x, int y) {
  3. return x + y;
  4. }
  5. public static void main(String[] args) {
  6. int z = myMethod(5, 3);
  7. System.out.println(z);
  8. }
  9. }

If…Else 的方法

通常在方法中使用 if…else 语句:

实例
  1. public class Main {
  2. // Create a checkAge() method with an integer parameter called age
  3. static void checkAge(int age) {
  4. // If age is less than 18, print "access denied"
  5. if (age < 18) {
  6. System.out.println("Access denied - You are not old enough!");
  7. // If age is greater than, or equal to, 18, print "access granted"
  8. } else {
  9. System.out.println("Access granted - You are old enough!");
  10. }
  11. }
  12. public static void main(String[] args) {
  13. checkAge(20); // Call the checkAge method and pass along an age of 20
  14. }
  15. }