Sub topic 2
Pass Arguments to Parameters
A method can do the same job with different information each time it runs. For example, a ticket-printing method can print a ticket for Ava, then print another for Noah.
A parameter is a named variable in a method’s declaration. It receives a value when the method is called. An argument is the value or expression supplied in the call.
Parameters and arguments matter because they let you reuse a method without writing a new one for every guest, number, or message.
See parameters and arguments in action
The following program prints two tickets and a route. Save it in a file named TicketDemo.java.
class TicketDemo {
static void printHeading() {
System.out.println("Tickets");
}
static void printTicket(String name, int row, double price) {
System.out.println("Name: " + name);
System.out.println("Row: " + row);
System.out.println("Price: " + price);
}
static void printRoute(String from, String to) {
System.out.println(from + " to " + to);
}
public static void main(String[] args) {
String guest = "Ava";
int firstRow = 4;
double ticketPrice = 12.5;
printHeading();
printTicket(guest, firstRow + 1, ticketPrice);
printTicket("Noah", 2, 10);
printRoute("Lima", "Oslo");
}
}To run it, open a terminal in the folder containing the file. A terminal is a place where you enter commands. Run:
javac TicketDemo.java
java TicketDemoThe javac command checks and compiles the program. Compiling means translating Java code into a form Java can run. The java command starts the program. You should see:
Tickets
Name: Ava
Row: 5
Price: 12.5
Name: Noah
Row: 2
Price: 10.0
Lima to OsloHere is the method declaration for a ticket:
static void printTicket(String name, int row, double price)
The method is named printTicket. Its parameters are inside the parentheses:
| Parameter | Type | Purpose |
|---|---|---|
| `name` | `String` | The guest’s name |
| `row` | `int` | The seat row |
| `price` | `double` | The ticket price |
A type describes what kind of value a variable can hold. String holds text, int holds whole numbers, and double holds numbers that can have a decimal part. The words static and void are not parameters. For now, note that void means this method does not return a value.
Inside the method body, the code uses name, row, and price. The method body is the set of statements between the braces after the declaration.
Follow a call step by step
Look at the first ticket call:
printTicket(guest, firstRow + 1, ticketPrice);
The three arguments are guest, firstRow + 1, and ticketPrice. An expression is a piece of code that produces a value. Java works out the argument values from left to right before the method body runs:
guestgives the text"Ava".firstRow + 1gives5, becausefirstRowis4.ticketPricegives12.5.- The values are supplied to
name,row, andprice, in that order. - The method body prints the ticket.
The argument names do not have to match the parameter names. In this call, guest supplies the value for name. The position of the argument makes the match.
The second call supplies different values:
printTicket("Noah", 2, 10);
This time, name receives "Noah", row receives 2, and price receives 10.0. The method body runs again with those values. Each call supplies its own parameter values.
Match the number and order
For this printTicket method, a call needs exactly three arguments. It also needs them in the order given by the declaration:
- Text for
name. - A whole number for
row. - A number suitable for
price.
For example, printTicket("Ava", 4, 12.5) matches all three positions. The call printTicket("Ava", 4) is missing an argument, so it will not compile.
A comma separates each parameter in a declaration and each argument in a call. There is no comma after the last one.
Same types can hide an order mistake
Look at the route method:
static void printRoute(String from, String to)
Both parameters have the same type. The call printRoute("Lima", "Oslo") prints Lima to Oslo.
The call printRoute("Oslo", "Lima") also compiles, but it prints the route in the opposite direction. Java can check that both arguments are text. It cannot know which city you intended as the starting point.
Java matches these arguments by position. It does not use labels such as from: and to: in a method call.
Match argument types
An argument’s value must be suitable for the type of its parameter. For example, the name parameter expects a String, so you can pass "Ava" or a String variable such as guest.
Text written directly in Java code uses double quotes. Without quotes, Ava would be read as a name in the program, not as the text "Ava".
The row parameter expects an int. The call printTicket("Ava", 2.5, 10) will not compile because 2.5 has a decimal part and is not an int. Use a whole-number row, such as 2.
Java allows some number values to be used with a different number type. In the example, the last argument of printTicket("Noah", 2, 10) is the whole number 10. Java can use that int value for the double parameter price, so it prints as 10.0.
Do not rely on Java to turn text into a number automatically. For example, "10" is text, not the number 10, so it cannot be passed directly to the double price parameter.
Use values, variables, and expressions
An argument does not have to be a value written directly in the call. These are all useful ways to supply one:
| Argument | What it supplies |
|---|---|
| `"Ava"` | A text value written directly |
| `guest` | The current value of a variable |
| `firstRow + 1` | The result of an expression |
The expression is worked out when the call runs. In the ticket example, firstRow + 1 produces 5. Writing that expression does not change firstRow; it is still 4.
Keep argument expressions easy to read. If a calculation is long, you can first store its result in a clearly named variable, then pass that variable to the method. This makes it easier to check what each argument means.
Call a method with no arguments
Not every method needs information from its caller. In the example, printHeading has no parameters:
static void printHeading()
Its call also has empty parentheses:
printHeading();
The parentheses are still needed. They show that the method is being called. The method simply prints the same heading each time.
You may also notice String[] args in main. That is a parameter too. String[] means an array of strings. An array holds a fixed number of values of the same type. When Java starts the program, it supplies command-line text through args; this example does not use it.
Check a call before running
If a method call does not compile or gives an unexpected result, check these points:
- Find the method declaration. Count its parameters.
- Count the arguments in the call. For the methods in this chapter, the counts must match.
- Match each argument to a parameter by position.
- Check that each argument’s value is suitable for the parameter’s type.
- Even when the types match, check that the values have the intended meanings.
The last step catches mistakes such as swapping the two cities in printRoute. A successful compile is useful, but it does not prove that the argument order makes sense.
Practice
Exercise
In the example program, what does printTicket("Mia", 3 + 2, 8) print?
Show answer
It prints Name: Mia, Row: 5, and Price: 8.0 on separate lines. The expression 3 + 2 supplies 5, and the int value 8 is accepted for the double parameter.
Exercise
What is wrong with printTicket("Mia", 8), and how could you fix it?
Show answer
The call has only two arguments, but printTicket has three parameters. Add a price, for example: printTicket("Mia", 8, 12.5);
Exercise
The intended route starts in Lima and ends in Oslo. Why is printRoute("Oslo", "Lima") a mistake even though it compiles?
Show answer
Both arguments are strings, so their types match. But their positions are reversed: from receives Oslo and to receives Lima. Use printRoute("Lima", "Oslo") instead.