The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Learning the Java Language
Lesson: Classes and Inheritance

Passing Information into a Method or a Constructor

The declaration for a method or a constructor declares the number and the type of the arguments for that method or constructor. For example, the following is a method that computes the monthly payments for a home loan, based on the amount of the loan, the interest rate, the length of the loan (the number of periods), and the future value of the loan:
public double computePayment(double loanAmt,
                             double rate,
                             double futureValue,
                             int numPeriods) {
    double interest = rate / 100.0;
    double partial1 = Math.pow((1 + interest), -numPeriods);
    double denominator = (1 - partial1) / interest;
    double answer = (-loanAmt / denominator)
                    - ((futureValue * partial1) / denominator);
    return answer;
}
This method takes four arguments: the loan amount, the interest rate, the future value and the number of periods. The first three are double-precision floating point numbers, and the fourth is an integer.

As with this method, the set of valid arguments is determined by a comma-separated list of parameters, where each parameter is a type/name pair. As you can see from the body of the computePayment method, you simply use the parameter name to refer to the arguments.

Argument Types

You can pass an argument of any data type into a method or a constructor. This includes primitive data types, such as doubles, floats, and integers, as you saw in the computePayment method, and reference data types, such as classes and arrays. Here's an example of a factory method that accepts an array as an argument. In this example, the method creates a new Polygon object and initializes it from an array of Points (assume that Point is a class that represents an x, y coordinate):
public static Polygon polygonFrom(Point[] listOfPoints) {
    ...
}
The ability to pass an arbitrary number of values to a method, also called varargs (introduced in J2SE 5.0), is useful when you don't know how many of a particular type of object will be passed to the method. It's a shortcut to creating an array manually. The previous method could use varargs rather than an array:
public static Polygon polygonFrom(Point... listOfPoints) {
    ...
}
Inside the method, listOfPoints behaves like an array. The method can be called either with an array or with a sequence of parameters.

You will most commonly see varargs with the printing methods; for example, the printf method:

public PrintStream printf(String format, Object... args)
can then be called like this:

System.out.printf("%s: %d, %s%n", name, idnum, address);

The Java programming language doesn't let you pass methods into methods. But you can pass an object into a method and then invoke the object's methods.

Argument Names

When you declare an argument to a method or a constructor, you provide a name for that argument. This name is used within the method body to refer to the data.

The name of an argument must be unique in its scope. It cannot be the same as the name of another argument for the same method or constructor, the name of a local variable within the method or constructor, or the name of any parameter to a catch clause within the same method or constructor.

An argument can have the same name as one of the class's member variables. If this is the case, the argument is said to hide the member variable. Hiding member variables can make your code difficult to read and is conventionally used only within constructors and methods that set a particular member variable. For example, consider the following Circle class and its setOrigin method:

public class Circle {
    private int x, y, radius;
    public void setOrigin(int x, int y) {
        ...
    }
}
The Circle class has three member variables: x, y, and radius. The setOrigin method accepts two arguments, each of which has the same name as one of the member variables. Each method argument hides the member variable that shares its name. So using the simple names x or y within the body of the method refers to the argument, not to the member variable. To access the member variable, you must use a qualified name. See the Using the this Keyword (in the Learning the Java Language trail) section for details.

Pass by Value

Primitive arguments, such as an int or an array, are passed by value, the rest are passed by reference. When invoked, a method or a constructor receives the value of the variable passed in and the method cannot change its value.

To get a better idea of what this means, let's look at a method called getRGBColor within a class called Pen. This method is attempting to return three values by setting the values of its arguments:

public class Pen {
    private int redValue, greenValue, blueValue;
    ...
    //This method does not work as intended.
    public void getRGBColor(int red, int green, int blue) {
        red = redValue;
        green = greenValue;
        blue = blueValue;
    }
}
This simply does not work. The red, green, and blue variables exist only within the scope of the getRGBColor method. When that method returns, those variables are gone and any changes to them lost.

Let's rewrite the getRGBColor method so that it does what was intended. First, we need a new type of object, RGBColor, that can hold the red, green, and blue values of a color in RGB space:

public class RGBColor {
    public int red, green, blue;
}
Now we can rewrite getRGBColor so that it accepts an RGBColor object as an argument. The getRGBColor method returns the current color of the pen by setting the red, green, and blue member variables of its RGBColor argument:
public class Pen {
    private int redValue, greenValue, blueValue;
    ...
    public void getRGBColor(RGBColor aColor) {
        aColor.red = redValue;
        aColor.green = greenValue;
        aColor.blue = blueValue;
    }
}
The changes made to the RGBColor object within the getRGBColor method persist after the method returns, because aColor is a reference to an object that exists outside the scope of the method.

Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.