Lesson 4.3 Arguments
Methods and Arguments
Most methods require additional information to carry out their work. A method that computes square roots, for instance, requires the number to operate on.
A method like bigBlueButton(), from Lesson 4.2, "Producing Values", would be much more useful if you could specify the text it should contain. Fortunately, that's very easy to accomplish by writing your method so that it accepts arguments, and then passing different values when you actually call the method.
In this lesson you'll learn:
- the difference between formal and actual arguments.
- how to define methods that take a single argument.
- how arguments are passed by value to a method.
- the difference between passing primitive and reference arguments.
- how type-checking is used in argument passing.
- how to pass multiple arguments to a method.
What are Arguments?
A formal argument is a local variable, specifically designed to store information that is sent to a method. A regular local variable is declared like this:
public void myMethod()
{
int myLocalVar = 32;
} |
As you remember, a variable declaration creates a "bucket" where you can store a value--in this case an int-sized bucket that can hold an int value--and initialization stores a value in the bucket. A formal argument works exactly like this local variable except:
- It is declared inside the argument list--that is, inside the parentheses following the method name--and not inside the method body.
- It is not initialized by using the assignment operator. Instead, it is initialized when the method is called.
After adding a formal argument to myMethod(), it would look like this:
public void myMethod(double myArg)
{
int myLocalVar = 32;
} |
To initialize the formal argument myArg, you can pass different values as actual arguments. Actual arguments are values you supply when you call the method. The actual arguments are used to initialize the formal arguments. If you look closely at myMethod() you'll see that the local variable myLocalVar will have the value 32 every time that myMethod() is called. In contrast, the variable myArg may have a different value each time myMethod() is called. This means that by calling myMethod() using different actual arguments, you can customize the way that myMethod() behaves. Let's see how this works by writing a new, improved version of the bigBlueButton() factory method.
A Single-Argument Method
Writing a method that takes a single argument is as easy as 1-2-3. Here are the steps:
Step 1: Method Header
The first step is to modify your method header so that you can supply the text necessary to customize your buttons. That means you'll have to declare a String variable to act as the formal argument in the bigBlueButton() argument list.
The previous definition of bigBlueButton() looked like this:
| public Button bigBlueButton() |
The new, improved version looks like this:
| public Button bigBlueButton(String text) |
Step 2: Method Body
Inside the method, use the new formal argument to intialize the local Button object. The previous version looked like this:
| Button b = new Button("I'm Blue"); |
Using the formal argument inside the method body, the new version looks like this:
| Button b = new Button(text); |
Step 3: Call the Method
When you call your method, pass the actual values you want to use. The BlueButtons applet from Lesson 4.2 had these three intitializations:
Button b1 = bigBlueButton();
Button b2 = bigBlueButton();
Button b3 = bigBlueButton(); |
But, afterward, in the init() method, you had to change the text of each Button like this; otherwise all of your Buttons would simply say "I'm Blue". [That might not be much worse than what they actually say, I agree.]
b1.setLabel("I'm FIRST");
b2.setLabel("I'm BLUEST");
b3.setLabel("I'm LAST"); |
Using the new, improved version of bigBlueButton() you can replace the previous six lines with these three:
Button b1 = bigBlueButton("I'm FIRST");
Button b2 = bigBlueButton("I'm BLUEST");
Button b3 = bigBlueButton("I'm LAST"); |
Pass By Value
When you call a method, the formal argument gets a copy of the actual argument. This is called pass by value. The actual arguments you use may be either literals or variables.
When you pass a variable, the value in the variable is copied into the formal argument that receives it. Because of this, calling a method cannot accidentally modify a variable used as an argument. In this example [click to expand], the two int variables a and b contain the values 52 and 17, respectively. When you pass the variables a and b to the method doSomethingWith(), the values 52 and 17 are copied into the formal arguments j and k. Inside the method, j and k are changed, but a and b are not affected at all.
Good Arguments
When you call a method, the actual arguments you pass must be compatible with the formal arguments. Java will attempt to ensure this using a process called type-checking.
Generally what this means is that if assignment would succeed then the method call will also succeed. You can normally assign a smaller or less precise value to a more precise variable.
Here are some examples of acceptable primitive arguments that may help you:
|
Formal Args
Acceptable Args
|
Unacceptable Args
|
| bytebyte |
everything else |
| shortbyte, short |
everything else |
| intbyte, short, int, char |
everything else |
| longbyte, short, int, char, long |
float, double |
| charbyte, short |
everything else |
| floatfloat, all integer types |
double |
| doubleall numeric types |
none |
Object Arguments
You can pass object variables and Strings to methods as well as primitive values. Object variables are passed by value, just as primitive types are; a copy is made of the object variable, and that copy is stored in the method's formal argument.
With object variables, however, the ultimate effect is a little different than when primitive types are passed by value. Remember that an object variable does not contain an object, it refers to one. Thus, when a copy of an object variable is made, only this reference is copied, and both object variables then refer to the same object like this: [click the image to expand]
Expressions as Actual Arguments
As long as the type is correct, actual arguments, whether primitive or object, can be:
- Variables Constants
- Expressions
Rather than creating a separate String variable when converting the contents of a TextField to a Double object, for instance, you could pass an expression like this:
| Double d = new Double(theText.getText()); |
Multiple Arguments
When a method has multiple formal arguments, the syntax for declaring those arguments is a little different than the syntax for declaring multiple local variables.
For instance, if your method contains two int local variables named x and y, you could declare those variables like this:
public void myMethod()
{
int x, y;
} |
When you declare two int parameters named x and y however, [parameter is another name for a formal argument], you cannot declare them in the same way. Instead, you must supply a type for each formal argument, even if the type of all formal arguments is the same, like this:
public void myMethod(int x, int y)
{
} |
Each type-name pair is separated from the others by a comma; thus, if you have two arguments, you need one comma, if you have three arguments, you need two commas, and so on.
The makeButton() Method
Let's put this information to work creating a method named makeButton(), similar to bigBlueButton(), that can make buttons of any color, using any font size.
You already saw how to change bigBlueButton() so that each button it produced had a customized inscription. What information do you need to pass to makeButton() so that it can perform these added tasks? You need to pass in three pieces of information:
- The text to display on the button. For that you'll use a String argument, just like in bigBlueButton(). The size of the font. For this, you'll use an int variable, although a byte would be big enough for any reasonably sized font. Generally, if you need an integer-style argument, use an int, not a short or a byte.
- The color of the text. For this, you'll use a Color object. You can look up the different color constants available in the JDK documentation under java.awt.Color. Later, you'll learn how to create your own custom colors as well.
Here's the modification of bigBlueButton() that meets those requirements along with an applet, Buttons.java, that uses the makeButton() method.
public Button makeButton( String text,
int fontSize,
Color bColor)
{
Font f;
f = new Font("SansSerif",
Font.BOLD,
fontSize);
Button b = new Button(text);
b.setFont(f);
b.setForeground(bColor);
return b;
}
|
Something to Talk About
Here are two exercises to try out your method-writing skills. How would you write these two methods? [Don't worry about the surrounding class.]
- The method fourthPower() which takes a single double argument and returns its argument raised to the fourth power as a double.
- The method echoIt() which takes three String arguments and returns a String consisting of two copies of the first argument, three copies of the second, and four copies of the third. [echoIt("Get","over","it"); returns the String "GetGetoveroveroveritititit"]
Please continue to the next section of this lesson.
|