Java Reference
In-Depth Information
double totalPrice = bobPrice + peterPrice ;
System. out . println ( "Total price for the project:
$" + totalPrice);
static double callBob( int width , int length)
System. out . println ( "Paint room" );
double pricePSF = 0.80;
return pricePSF width
length ;
public static double callPeter( int width , int length)
System. out . println ( "Install hardwood floor" );
double pricePSF = 3.20;
return pricePSF
length ;
Now we send the dimensions of the room to our friends. Bob charges 80c/foot for paint-
ing, while Peter charges
3.20 for hardwood flooring. Note that the variables width and
length are local variables for both methods. That is, these variables are only defined inside
the methods. When the callBob method is called, width becomes equal to 8 and length
becomes equal to 12. The two values are used to calculate the total cost of the job. After
the method terminates, the variables are destroyed. These variables are called automatic
because space for them is automatically created at the beginning of the method and they
are automatically destroyed at the end of the method in which they are defined.
A formal parameter of a method is a variable that is defined between the paren-
theses in the signature of the method. An actual parameter of a method is the value
that is passed to the method.
In the callBob method, the variables width and length are the formal parameters.
Consider the following code.
int x=3;
int y=5;
callBob(x,y) ;
The variables x and y are the actual parameters. The values 3 and 5 are passed to the
callBob method. Note that the callBob method cannot change the values of the variables
x and y because it does not have access to them. The callBob method only has access to
their values.
Any changes to the value of the formal parameters of a method do not affect the
actual parameters. The reason is that in Java, methods are called by value. Only the
values of the actual parameters are sent to a method.
After Bob finishes painting the room, he will send us the bill. He does that by calling
the return command. Note that the command performs two tasks. First, as we have seen
before, it terminates the current method. Any code after calling the return statement will
not be executed. The control is transferred back to the calling method (in this case, the
main method). Second, the return method can send back information. In this case, the
method will send back 76 . 80, which is the price that is charged by Bob.
Search WWH ::

Custom Search