Search code examples
javamethodsparametersargumentsencapsulation

How to use parameters and arguments in java?


I don't understand the connect or the difference between parameters and arguments. Can you use either as a method? How do you return an argument? Any help is greatly appreciated.


Solution

  • Warning: a lot of people don't differentiate between "parameter" and "argument". They should, but they don't - so you may well see a lot of pages with incorrect uses of the terms.

    When you declare a method or constructor, the parameters are the bits you put in declarations to receive values to work with. For example:

    public void foo(int x, int y)
    

    Here x and y are the parameters. Within the method, they just act like local variables.

    When you call a method or constructor, the arguments are the values that you pass in. Those act as the initial values of the parameters. So for example:

    foo(5, 3);
    

    Here 5 and 3 are the arguments - so the parameter x will start with a value of 5, and the parameter y will start with a value of 3. Of course, you can use a parameter (or any other variable) as an argument too. For example:

    public void foo(int x, int y) {
        System.out.println(y);
    }
    

    Here y is a parameter in the foo method, but its value is being used as the argument to the println method.

    Can you use either as a method?

    No, they're a completely different concept.

    How do you return an argument?

    Again, that doesn't really make sense. You can use the value of a parameter in a return statement though:

    public int foo(int x, int y) {
        // Normally you'd use y for something, of course
        return x;
    }