Declaring a Method with a Parameter
In our car analogy from Section 3.2, we discussed the fact that pressing a car's gas pedal sends a message to the car to perform a taskmake the car go faster. But how fast should the car accelerate? As you know, the farther down you press the pedal, the faster the car accelerates. So the message to the car actually includes the task to perform and additional information that helps the car perform the task. This additional information is known as a parameterthe value of the parameter helps the car determine how fast to accelerate. Similarly, a method can require one or more parameters that represent additional information it needs to perform its task. A method call supplies valuescalled argumentsfor each of the method's parameters. For example, the method System.out.println requires an argument that specifies the data to output in a command window. Similarly, to make a deposit into a bank account, a deposit method specifies a parameter that represents the deposit amount. When the deposit method is called, an argument value representing the deposit amount is assigned to the method's parameter. The method then makes a deposit of that amount.
Our next example declares class GradeBook (Fig. 3.4) with a displayMessage method that displays the course name as part of the welcome message. (See the sample execution in Fig. 3.5.) The new displayMessage method requires a parameter that represents the course name to output.
Figure 3.4. Class declaration with one method that has a parameter.
1 // Fig. 3.4: GradeBook.java 2 // Class declaration with a method that has a parameter. 3 4 public class GradeBook 5 { 6 // display a welcome message to the GradeBook user 7 public void displayMessage( String courseName ) 8 { 9 System.out.printf( "Welcome to the grade book for %s! ", 10 courseName ); 11 } // end method displayMessage 12 13 } // end class GradeBook |
Figure 3.5. Creating a GradeBook object and passing a String to its displayMessage method.
(This item is displayed on page 89 in the print version)
1 // Fig. 3.5: GradeBookTest.java 2 // Create GradeBook object and pass a String to 3 // its displayMessage method. 4 import java.util.Scanner; // program uses Scanner 5 6 public class GradeBookTest 7 { 8 // main method begins program execution 9 public static void main( String args[] ) 10 { 11 // create Scanner to obtain input from command window 12 Scanner input = new Scanner( System.in ); 13 14 // create a GradeBook object and assign it to myGradeBook 15 GradeBook myGradeBook = new GradeBook(); 16 17 // prompt for and input course name 18 System.out.println( "Please enter the course name:" ); 19 String nameOfCourse = input.nextLine(); // read a line of text 20 System.out.println(); // outputs a blank line 21 22 // call myGradeBook's displayMessage method 23 // and pass nameOfCourse as an argument 24 myGradeBook.displayMessage( nameOfCourse ); 25 } // end main 26 27 } // end class GradeBookTest
|
Before discussing the new features of class GradeBook, let's see how the new class is used from the main method of class GradeBookTest (Fig. 3.5). Line 12 creates a Scanner named input for reading the course name from the user. Line 15 creates an object of class GradeBook and assigns it to variable myGradeBook. Line 18 prompts the user to enter a course name. Line 19 reads the name from the user and assigns it to the nameOfCourse variable, using Scanner method nextLine to perform the input. The user types the course name and presses Enter to submit the course name to the program. Note that pressing Enter inserts a newline character at the end of the characters typed by the user. Method nextLine reads characters typed by the user until the newline character is encountered, then returns a String containing the characters up to, but not including, the newline. The newline character is discarded. Note that Scanner provides a similar methodnextthat reads individual words. When the user presses Enter after typing input, method next reads characters until a white-space character (such as a space, tab or newline) is encountered, then returns a String containing the characters up to, but not including, the white-space character (which is discarded). All information after the first white-space character is not lostit can be read by other statements that call the Scanner's methods later in the program.
Line 24 calls myGradeBooks's displayMessage method. The variable nameOfCourse in parentheses is the argument that is passed to method displayMessage so that the method can perform its task. The value of variable nameOfCourse in main becomes the value of method displayMessage's parameter courseName in line 7 of Fig. 3.4. When you execute this application, notice that method displayMessage outputs the name you type as part of the welcome message (Fig. 3.5).
Software Engineering Observation 3.1
Normally, objects are created with new. One exception is a string literal that is contained in quotes, such as "hello". String literals are references to String objects that are implicitly created by Java. |
More on Arguments and Parameters
When you declare a method, you must specify in the method's declaration whether the method requires data to perform its task. To do so, you place additional information in the method's parameter list, which is located in the parentheses that follow the method name. The parameter list may contain any number of parameters, including none at all. Empty parentheses following the method name (as in Fig. 3.1, line 7) indicate that a method does not require any parameters. In Fig. 3.4, displayMessage's parameter list (line 7) declares that the method requires one parameter. Each parameter must specify a type and an identifier. In this case, the type String and the identifier courseName indicate that method displayMessage requires a String to perform its task. At the time the method is called, the argument value in the call is assigned to the corresponding parameter (in this case, courseName) in the method header. Then, the method body uses the parameter courseName to access the value. Lines 910 of Fig. 3.4 display parameter courseName's value, using the %s format specifier in printf's format string. Note that the parameter variable's name (Fig. 3.4, line 7) can be the same or different from the argument variable's name (Fig. 3.5, line 24).
A method can specify multiple parameters by separating each parameter from the next with a comma (we'll see an example of this in Chapter 6). The number of arguments in a method call must match the number of parameters in the parameter list of the called method's declaration. Also, the argument types in the method call must be consistent with the types of the corresponding parameters in the method's declaration. (As you will learn in subsequent chapters, an argument's type and its corresponding parameter's type are not always required to be identical.) In our example, the method call passes one argument of type String (nameOfCourse is declared as a String on line 19 of Fig. 3.5) and the method declaration specifies one parameter of type String (line 7 in Fig. 3.4). So the type of the argument in the method call exactly matches the type of the parameter in the method header.
Common Programming Error 3.2
A compilation error occurs if the number of arguments in a method call does not match the number of parameters in the method declaration. |
Common Programming Error 3.3
A compilation error occurs if the types of the arguments in a method call are not consistent with the types of the corresponding parameters in the method declaration. |
Updated UML Class Diagram for Class GradeBook
The UML class diagram of Fig. 3.6 models class GradeBook of Fig. 3.4. Like Fig. 3.1, this GradeBook class contains public operation displayMessage. However, this version of displayMessage has a parameter. The UML models a parameter a bit differently from Java by listing the parameter name, followed by a colon and the parameter type in the parentheses following the operation name. The UML has its own data types similar to those of Java (but as you will see, not all the UML data types have the same names as the corresponding Java types). The UML type String does correspond to the Java type String. Method displayMessage of class GradeBook (Fig. 3.4) has a String parameter named courseName, so Fig. 3.6 lists courseName : String between the parentheses following displayMessage.
Figure 3.6. UML class diagram indicating that class GradeBook has a displayMessage operation with a courseName parameter of UML type String.
(This item is displayed on page 90 in the print version)
Notes on import Declarations
Notice the import declaration in Fig. 3.5 (line 4). This indicates to the compiler that the program uses class Scanner. Why do we need to import class Scanner, but not class System, String or class GradeBook? Most classes you will use in Java programs must be imported. Classes System and String are in package java.lang, which is implicitly imported into every Java program. Thus, all programs can use package java.lang's classes without explicitly importing them.
There is a special relationship between classes that are compiled in the same directory on disk, like classes GradeBook and GradeBookTest. By default, such classes are considered to be in the same packageknown as the default package. Classes in the same package are implicitly imported into the source code files of other classes in the same package. Thus, an import declaration is not required when one class in a package uses another in the same packagesuch as when class GradeBookTest uses class GradeBook.
Actually, the import declaration at line 4 is not required if we always refer to class Scanner as java.util.Scanner, which includes the full package name and class name. This is known as the class's fully qualified class name. For example, line 12 could be written as
java.util.Scanner input = new java.util.Scanner( System.in );
Software Engineering Observation 3.2
The Java compiler does not require import declarations in a Java source code file if the fully qualified class name is specified every time a class name is used in the source code. But most Java programmers consider using fully qualified names to be cumbersome, and instead prefer to use import declarations. |