Declaring Methods with Multiple Parameters
Chapters 35 presented classes containing simple methods that had at most one parameter. Methods often require more than one piece of information to perform their tasks. We now consider how programmers write their own methods with multiple parameters.
The application in Fig. 6.3 and Fig. 6.4 uses a programmer-declared method called maximum to determine and return the largest of three double values that are input by the user. When the application begins execution, class MaximumFinderTest's main method (lines 711 of Fig. 6.4) creates one object of class MaximumFinder (line 9) and calls the object's determineMaximum method (line 10) to produce the program's output. In class MaximumFinder (Fig. 6.3), lines 1418 of method determineMaximum prompt the user to enter three double values and read them from the user. Line 21 calls method maximum (declared in lines 2841) to determine the largest of the three double values passed as arguments to the method. When method maximum returns the result to line 21, the program assigns maximum's return value to local variable result. Then line 24 outputs the maximum value. At the end of this section, we'll discuss the use of operator + in line 24.
Figure 6.3. Programmer-declared method maximum that has three double parameters.
(This item is displayed on page 237 in the print version)
1 // Fig. 6.3: MaximumFinder.java 2 // Programmer-declared method maximum. 3 import java.util.Scanner; 4 5 public class MaximumFinder 6 { 7 // obtain three floating-point values and locate the maximum value 8 public void determineMaximum() 9 { 10 // create Scanner for input from command window 11 Scanner input = new Scanner( System.in ); 12 13 // obtain user input 14 System.out.print( 15 "Enter three floating-point values separated by spaces: " ); 16 double number1 = input.nextDouble(); // read first double 17 double number2 = input.nextDouble(); // read second double 18 double number3 = input.nextDouble(); // read third double 19 20 // determine the maximum value 21 double result = maximum( number1, number2, number3 ); 22 23 // display maximum value 24 System.out.println( "Maximum is: " + result ); 25 } // end method determineMaximum 26 27 // returns the maximum of its three double parameters 28 public double maximum( double x, double y, double z ) 29 { 30 double maximumValue = x; // assume x is the largest to start 31 32 // determine whether y is greater than maximumValue 33 if ( y > maximumValue ) 34 maximumValue = y; 35 36 // determine whether z is greater than maximumValue 37 if ( z > maximumValue ) 38 maximumValue = z; 39 40 return maximumValue; 41 } // end method maximum 42 } // end class MaximumFinder |
Figure 6.4. Application to test class MaximumFinder.
(This item is displayed on page 238 in the print version)
1 // Fig. 6.4: MaximumFinderTest.java 2 // Application to test class MaximumFinder. 3 4 public class MaximumFinderTest 5 { 6 // application starting point 7 public static void main( String args[] ) 8 { 9 MaximumFinder maximumFinder = new MaximumFinder(); 10 maximumFinder.determineMaximum(); 11 } // end main 12 } // end class MaximumFinderTest
|
Consider the declaration of method maximum (lines 2841). Line 28 indicates that the method returns a double value, that the method's name is maximum and that the method requires three double parameters (x, y and z) to accomplish its task. When a method has more than one parameter, the parameters are specified as a comma-separated list. When maximum is called from line 21, the parameter x is initialized with the value of the argument number1, the parameter y is initialized with the value of the argument number2 and the parameter z is initialized with the value of the argument number3. There must be one argument in the method call for each parameter (sometimes called a formal parameter) in the method declaration. Also, each argument must be consistent with the type of the corresponding parameter. For example, a parameter of type double can receive values like 7.35, 22 or 0.03456, but not Strings like "hello". Section 6.7 discusses the argument types that can be provided in a method call for each parameter of a primitive type.
To determine the maximum value, we begin with the assumption that parameter x contains the largest value, so line 30 declares local variable maximumValue and initializes it with the value of parameter x. Of course, it is possible that parameter y or z contains the actual largest value, so we must compare each of these values with maximumValue. The if statement at lines 3334 determines whether y is greater than maximumValue. If so, line 34 assigns y to maximumValue. The if statement at lines 3738 determines whether z is greater than maximumValue. If so, line 38 assigns z to maximumValue. At this point the largest of the three values resides in maximumValue, so line 40 returns that value to line 21. When program control returns to the point in the program where maximum was called, maximum's parameters x, y and z no longer exist in memory. Note that methods can return at most one value, but the returned value could be a reference to an object that contains many values.
Note that result is a local variable in determineMaximum because it is declared in the block that represents the method's body. Variables should be declared as fields of a class only if they are required for use in more than one method of the class or if the program should save their values between calls to the class's methods.
Common Programming Error 6.1
Declaring method parameters of the same type as float x, y instead of float x, float y is a syntax errora type is required for each parameter in the parameter list. |
Software Engineering Observation 6.5
A method that has many parameters may be performing too many tasks. Consider dividing the method into smaller methods that perform the separate tasks. As a guideline, try to fit the method header on one line if possible. |
Implementing Method maximum by Reusing Method Math.max
Recall from Fig. 6.2 that class Math has a max method that can determine the larger of two values. The entire body of our maximum method could also be implemented with two calls to Math.max, as follows:
return Math.max( x, Math.max( y, z ) );
The first call to Math.max specifies arguments x and Math.max( y, z ). Before any method can be called, all its arguments must be evaluated to determine their values. If an argument is a method call, the method call must be performed to determine its return value. So, in the preceding statement, Math.max( y, z ) is evaluated first to determine the maximum of y and z. Then the result is passed as the second argument to the other call to Math.max, which returns the larger of its two arguments. Using Math.max in this manner is a good example of software reusewe find the largest of three values by reusing Math.max, which finds the largest of two values. Note how concise this code is compared to lines 3040 of Fig. 6.3.
Assembling Strings with String Concatenation
Java allows String objects to be created by assembling smaller strings into larger strings using operator + (or the compound assignment operator +=). This is known as string concatenation. When both operands of operator + are String objects, operator + creates a new String object in which the characters of the right operand are placed at the end of those in the left operand. For example, the expression "hello " + "there" creates the String "hello there".
In line 24 of Fig. 6.3, the expression "Maximum is: " + result uses operator + with operands of types String and double. Every primitive value and object in Java has a String representation. When one of the + operator's operands is a String, the other is converted to a String, then the two are concatenated. In line 24, the double value is converted to its String representation and placed at the end of the String "Maximum is: ". If there are any trailing zeros in a double value, these will be discarded when the number is converted to a String. Thus, the number 9.3500 would be represented as 9.35 in the resulting String.
For primitive values used in string concatenation, the primitive values are converted to Strings. If a boolean is concatenated with a String, the boolean is converted to the String "true" or "false". All objects have a method named toString that returns a String representation of the object. When an object is concatenated with a String, the object's toString method is implicitly called to obtain the String representation of the object. You will learn more about method toString in Chapter 7, Arrays.
When a large String literal is typed into a program's source code, programmers sometimes prefer to break that String into several smaller Strings and place them on multiple lines of code for readability. In this case, the Strings can be reassembled using concatenation. We discuss the details of Strings in Chapter 29, Strings, Characters and Regular Expressions.
Common Programming Error 6.2
It is a syntax error to break a String literal across multiple lines in a program. If a String does not fit on one line, split the String into several smaller Strings and use concatenation to form the desired String. |
Common Programming Error 6.3
Confusing the + operator used for string concatenation with the + operator used for addition can lead to strange results. Java evaluates the operands of an operator from left to right. For example, if integer variable y has the value 5, the expression "y + 2 = " + y + 2 results in the string "y + 2 = 52", not "y + 2 = 7", because first the value of y (5) is concatenated with the string "y + 2 = ", then the value 2 is concatenated with the new larger string "y + 2 = 5". The expression "y + 2 = " + (y + 2) produces the desired result "y + 2 = 7". |