杰瑞科技汇

Java参数传递,值传递还是引用传递?

Of course! Here's a comprehensive guide to Java parameters, covering method parameters, command-line arguments, and best practices.


Method Parameters

This is the most common use of "parameters" in Java. Parameters are the variables listed inside the parentheses in the method definition. They act as placeholders for the values you will pass to the method when you call it.

Key Concepts:

  • Parameter: The variable in the method definition (e.g., int a in public static void add(int a)).
  • Argument: The actual value passed to the method when it's called (e.g., 5 in add(5)).

Example: Simple Method Parameters

Let's look at a basic method that takes two integer parameters and prints their sum.

public class ParameterExample {
    // This is the METHOD DEFINITION.
    // 'a' and 'b' are PARAMETERS.
    public static void addTwoNumbers(int a, int b) {
        int sum = a + b;
        System.out.println("The sum is: " + sum);
    }
    public static void main(String[] args) {
        System.out.println("Calling addTwoNumbers with arguments 10 and 20...");
        // This is a METHOD CALL.
        // 10 and 20 are ARGUMENTS.
        addTwoNumbers(10, 20);
        System.out.println("Calling addTwoNumbers with arguments 7 and 3...");
        addTwoNumbers(7, 3);
    }
}

Output:

Calling addTwoNumbers with arguments 10 and 20...
The sum is: 30
Calling addTwoNumbers with arguments 7 and 3...
The sum is: 10

Types of Parameters in Methods

a) Pass-by-Value

Java is strictly pass-by-value. This means that when you pass a parameter to a method, you are passing a copy of the value, not the original variable itself.

  • For Primitive Types (int, double, char, etc.): The method gets a copy of the primitive value. Any changes made to the parameter inside the method do not affect the original variable in the caller.

    public class PassByValuePrimitive {
        public static void modifyValue(int x) {
            x = 100; // This changes the copy of x, not the original.
            System.out.println("Inside method, x is: " + x);
        }
        public static void main(String[] args) {
            int originalValue = 10;
            System.out.println("Before method call, originalValue is: " + originalValue);
            modifyValue(originalValue);
            System.out.println("After method call, originalValue is: " + originalValue);
        }
    }

    Output:

    Before method call, originalValue is: 10
    Inside method, x is: 100
    After method call, originalValue is: 10
  • For Object References: The method gets a copy of the reference (the memory address) to the object. This means both the original reference and the copied reference point to the same object. Therefore, you can modify the object's state (its fields), but you cannot change the original reference to point to a different object.

    class Person {
        String name;
        Person(String name) {
            this.name = name;
        }
    }
    public class PassByValueObject {
        public static void modifyObject(Person p) {
            // This changes the state of the object that the reference 'p' points to.
            // The original 'myPerson' reference in main() will see this change.
            p.name = "Alice";
            // This reassigns the local reference 'p' to a new object.
            // The original 'myPerson' reference in main() is NOT affected.
            p = new Person("Bob");
        }
        public static void main(String[] args) {
            Person myPerson = new Person("Charlie");
            System.out.println("Before method call, myPerson's name is: " + myPerson.name);
            modifyObject(myPerson);
            System.out.println("After method call, myPerson's name is: " + myPerson.name);
        }
    }

    Output:

    Before method call, myPerson's name is: Charlie
    After method call, myPerson's name is: Alice

b) Varargs (Variable Arguments)

If you want a method to accept a variable number of arguments, you can use varargs. The syntax is (three dots) after the type.

public class VarargsExample {
    // This method can accept 0, 1, 2, or more integers.
    public static int sumAll(int... numbers) {
        int total = 0;
        for (int number : numbers) {
            total += number;
        }
        return total;
    }
    public static void main(String[] args) {
        System.out.println("Sum of nothing: " + sumAll()); // Works with 0 args
        System.out.println("Sum of 1 number: " + sumAll(5));
        System.out.println("Sum of 3 numbers: " + sumAll(1, 2, 3));
        System.out.println("Sum of 5 numbers: " + sumAll(10, 20, 30, 40, 50));
    }
}

Output:

Sum of nothing: 0
Sum of 1 number: 5
Sum of 3 numbers: 6
Sum of 5 numbers: 150

Command-Line Arguments

Command-line arguments are parameters passed to a main method when you run the Java program from the command line. They are stored in the String[] args array.

How to Use Them:

  1. Compile the code:

    javac Program.java
  2. Run the program with arguments:

    java Program hello world 123
  3. Code to access the arguments:

    public class CommandLineArgs {
        // The 'args' parameter is an array of Strings containing the command-line arguments.
        public static void main(String[] args) {
            // Check if any arguments were provided
            if (args.length == 0) {
                System.out.println("No command-line arguments provided.");
            } else {
                System.out.println("Number of arguments: " + args.length);
                System.out.println("Arguments are:");
                // Loop through the args array to print each argument
                for (int i = 0; i < args.length; i++) {
                    System.out.println("args[" + i + "]: " + args[i]);
                }
            }
        }
    }

Running the example:

java CommandLineArgs hello world 123

Output:

Number of arguments: 3
Arguments are:
args[0]: hello
args[1]: world
args[2]: 123

Best Practices for Method Parameters

  1. Use Meaningful Names: Don't use a, b, c. Use descriptive names like firstName, age, productId.

    // Bad
    public void process(String s, int i) { ... }
    // Good
    public void processCustomerOrder(String customerName, int orderQuantity) { ... }
  2. Limit the Number of Parameters: A method with more than 3-4 parameters can become hard to read and use. If you have many related parameters, consider creating a single class or record to hold them.

    // Bad - Too many parameters
    public void createUser(String name, String email, String address, String city, String country) { ... }
    // Good - Use a data object (record is a concise modern way)
    public record User(String name, String email, Address address) {}
    public record Address(String street, String city, String country) {}
    public void createUser(User user) { ... }
  3. Prefer Immutability: When passing objects, prefer passing immutable objects (like String, Integer, or custom classes with final fields). This prevents unintended side effects where the method changes the object's state.

  4. Document Your Parameters: Use Javadoc comments to explain what each parameter does, its expected type, and any constraints.

    /**
     * Calculates the total price of an order.
     *
     * @param items An array of item prices.
     * @param taxRate The sales tax rate (e.g., 0.08 for 8%).
     * @return The total price including tax.
     */
    public static double calculateTotal(double[] items, double taxRate) {
        // ... implementation
    }

Summary Table

Type What it is Example Pass Mechanism
Method Parameter Variable in a method definition. public void myMethod(int x) Pass-by-value (copy of value or reference).
Method Argument Value passed to a method during a call. myMethod(42); The actual data being passed.
Command-Line Argument Value passed to a program at runtime via the command line. java MyProgram arg1 Stored in the String[] args array of the main method.
分享:
扫描分享到社交APP
上一篇
下一篇