We now consider how to write your own methods with multiple parameters. Figure 6.2 uses a method calledmaximumto determine and return the largest ofthreedoublevalues. In
main, lines 14–18 prompt the user to enter threedoublevalues, then read them from the user. Line 21 calls methodmaximum(declared in lines 28–41) to determine the largest of the three values it receives as arguments. When methodmaximumreturns the result to line 21, the program assignsmaximum’s return value to local variableresult. Then line 24 outputs the maximum value. At the end of this section, we’ll discuss the use of operator + in line 24.
1 // Fig. 6.2: MaximumFinder.java
2 // Programmer-declared method maximum with three double parameters.
3 import java.util.Scanner;
4
5 public class MaximumFinder 6 {
7 // obtain three floating-point values and locate the maximum value 8 public static void main( String[] args )
9 {
10 // create Scanner for input from command window 11 Scanner input = new Scanner( System.in );
12
13 // prompt for and input three floating-point values 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
22
23 // display maximum value
24 System.out.println( );
25 } // end main 26
27 28 29 30 31
Fig. 6.2 | Programmer-declared methodmaximumwith threedoubleparameters. (Part 1 of 2.)
double result = maximum( number1, number2, number3 );
"Maximum is: " + result
// returns the maximum of its three double parameters
public static double maximum( double x, double y, double z ) {
double maximumValue = x; // assume x is the largest to start
6.4 Declaring Methods with Multiple Parameters 119
ThepublicandstaticKeywords
Methodmaximum’s declaration begins with keywordpublicto indicate that the method is
“available to the public”—it can be called from methods of other classes. The keyword
staticenables themainmethod (anotherstaticmethod) to callmaximumas shown in line 21 without qualifying the method name with the class nameMaximumFinder—static methods in the same class can call each other directly. Any other class that usesmaximum must fully qualify the method name with the class name.
Methodmaximum
Considermaximum’s declaration (lines 28–41). Line 28 indicates that it returns adouble value, that the method’s name ismaximumand that the method requires threedoublepa- rameters (x,yandz) to accomplish its task. Multiple parameters are specified as a comma- separated list. Whenmaximumis called from line 21, the parametersx,yandzare initial- ized with the values of argumentsnumber1, number2 and number3, respectively. There must be one argument in the method call for each parameter in the method declaration.
Also, each argument must beconsistentwith the type of the corresponding parameter. For example, a parameter of typedoublecan receive values like 7.35, 22 or –0.03456, but not
Strings like"hello"nor thebooleanvaluestrueorfalse. Section 6.6 discusses the ar- gument 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 parameterx contains the largest value, so line 30 declares local variablemaximumValueand initializes it with the value of parameterx. Of course, it’s possible that parameteryorzcontains the actual largest value, so we must compare each of these values withmaximumValue. Theif 32
33 34 35 36 37 38 39 40 41
42 } // end class MaximumFinder
Enter three floating-point values separated by spaces: 9.35 2.74 5.1 Maximum is: 9.35
Enter three floating-point values separated by spaces: 5.8 12.45 8.32 Maximum is: 12.45
Enter three floating-point values separated by spaces: 6.46 4.12 10.54 Maximum is: 10.54
Fig. 6.2 | Programmer-declared methodmaximumwith threedoubleparameters. (Part 2 of 2.)
// determine whether y is greater than maximumValue if ( y > maximumValue )
maximumValue = y;
// determine whether z is greater than maximumValue if ( z > maximumValue )
maximumValue = z;
return maximumValue;
} // end method maximum
120 Chapter 6 Methods: A Deeper Look
statement at lines 33–34 determines whetheryis greater thanmaximumValue. If so, line 34 assigns y to maximumValue. The if statement at lines 37–38 determines whether z is greater than maximumValue. If so, line 38 assignsz to maximumValue. At this point the largest of the three values resides inmaximumValue, so line 40 returns that value to line 21.
When program control returns to the point in the program wheremaximumwas called,
maximum’s parametersx,yandzno longer exist in memory.
Implementing Methodmaximumby Reusing MethodMath.max
The entire body of our maximum method could also be implemented with two calls to
Math.max, as follows:
The first call toMath.maxspecifies argumentsxandMath.max( y, z ).Beforeany method can be called, 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 to determine the maximum ofyand
z. Then the result is passed as the second argument to the other call toMath.max, which returns the larger of its two arguments. This is a good example of software reuse—we find the largest of three values by reusingMath.max, which finds the larger of two values. Note how concise this code is compared to lines 30–38 of Fig. 6.2.
Assembling Strings with String Concatenation
Java allows you to assembleStringobjects into larger strings by using operators+or+=. This is known asstring concatenation. When both operands of operator+areStringob- jects, operator+creates a newStringobject in which the characters of the right operand are placed at the end of those in the left operand—e.g., the expression"hello " + "there"
creates theString "hello there".
In line 24 of Fig. 6.2, the expression"Maximum is: " + resultuses operator+with operands of typesStringanddouble.Every primitive value and object in Java has aString representation.When one of the+operator’s operands is aString, the other is converted to aString, then the two areconcatenated. In line 24, thedoublevalue is converted to its
Stringrepresentation and placed at the end of theString "Maximum is: ". If there are any trailing zerosin adoublevalue, these will bediscardedwhen the number is converted to a
String—for example 9.3500 would be represented as 9.35.
Primitive values used inStringconcatenation are converted toStrings. Aboolean concatenated with aString is converted to theString "true" or"false". All objects have atoStringmethod that returns aStringrepresentation of the object. (We discuss
toStringin more detail in subsequent chapters.) When an object is concatenated with a Software Engineering Observation 6.3
Methods can return at most one value, but the returned value could be a reference to an object that contains many values.
Software Engineering Observation 6.4
Variables should be declared as fields only if they’re 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.
return Math.max( x, Math.max( y, z ) );