This chapter reviews method parameters and local variables, as well as method overloading and method signature.
Method overloading means two or more methods have the same name but have different parameter lists: either a different number of parameters or different types of parameters. When a method is called, the corresponding method is invoked by matching the arguments in the call to the parameter lists of the methods. The name together with the number and types of a method's parameter list is called the signature of a method. The return type itself is not part of the signature of a method.
9. Local Variables
Answer:
Is this OK?
Sure. The caller has sent the value 7000 to the method. Inside the method, that value is held in the parameter amount
. At the end of the method, the statement
amount = 0;
puts a zero into the parameter, but does not affect anything in main()
Local Variables
public class CheckingAccount { . . . . private int balance; public void processCheck( int amount ) { int charge; // scope of charge starts here incrementUse(); if ( balance < 100000 ) charge = 15; else charge = 0; balance = balance - amount - charge ; // scope of charge ends here } } |
A local variable is a variable that is declared inside of the body of a method.
The scope of a local variable starts from where it is declared and ends at the end of the block that it is in. Recall that a block is a group of statements inside of braces, {}
.
For example, charge
of processCheck
is a local variable:
The local variable charge
is used to hold a temporary value while something is being calculated. Local variables are not used to hold the permanent values of an object's state. They have a value only during the brief amount of time that a method is active.
Question 9:
Is the scope of a local variable always the entire body of a method?