Passing Arguments using Methods

From CompSciWiki
Revision as of 21:08, 13 March 2007 by Ummisur0 (Talk | contribs)

Jump to: navigation, search

An argument is a value passed to a method's parameter during a method call.

For example, consider the following method:

    public static int add(int x, int y)
    {
        int sum;
        sum = x + y;
        return sum;
    }

When you call the above method, you need to pass two int values to the method. Each value is an argument.

    public static void main(String[] args)
    {
        int result = add(16, 28);
    }

In the above example, the values 16 and 28 are arguments.

Argument Values

Three types of values may be used as arguments:

  1. Literal values, such as the String "Hello world!" or the double 52.8
  2. Variables (the variable must be the same type as the parameter)
  3. Other method calls (the return value of the passed method call must be the same type as the parameter)

Passing a method call as an argument to another method call creates a nested method call. For example, we can nest calls to the add method in this way:

public class NestedAdd
{
    public static int add(int x, int y)
    {
        int sum;
        sum = x + y;
        return sum;
    } 

    public static void main(String[] args)
    {
        int result;

        // This is our nested method call
        result = add(8, add(2, 3));
        System.out.println(result);

        result = add(8, 5);
        System.out.println(result);
    }
}

In this example, the result of add(2, 3) is used as an argument for another call to the add method. The output of the program is:

13
13


Order of Arguments

Arguments must be passed to a method call in the same order that the parameters are declared. The following program demonstrates a method call which requires two different argument types:

public class ArgumentOrder
{
    public static void printLines(String line, int numLines)
    {
        for(int i = 1; i <= numLines; i++)
        {
            System.out.println(i + " " + line);
        }
    }

    public static void main(String[] args)
    {
        printLines("Just a short line.", 5);
    }
}

The output will be:

1 Just a short line.
2 Just a short line.
3 Just a short line.
4 Just a short line.
5 Just a short line.

The printLines method requires a String argument and an int argument. The arguments are called in the order which the method header declares the parameters. Changing the call to printLines in the following way will result in a compile-time error:

        printLines(5, "Just a short line."); // Error! Program will not compile.

This will result in an error because the printLines method is expecting a String then an int, not an int followed by a String.