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.
12. Review: for Loops
Answer:
Yes. The variable that follows the reserved word this
is an instance variable (part of "this" object).
Review: for
Loops
for
Loops
Here is a for
loop:
{ int sum = 0; for ( int count = 0; count < 10; count++ ) { System.out.print( count + " " ); sum = sum+count; } }
Scope Rule: a variable declared in a for
statement can only be used in that statement and the body of the loop. The scope of count
is only the loop body.
The following is NOT correct:
{ int sum = 0; for ( int count = 0; count < 10; count++ ) { System.out.print( count + " " ); sum = sum+count; } // NOT part of the loop body System.out.println( "\nAfter the loop count is: " + count ); }
Since the println()
statement is not part of the loop body, count
cannot be used here. The compiler will complain that it "cannot find the symbol: count" when it sees this count
.
This can be a baffling error message if you forget the scope rule.
However, sum
is declared outside of the for
loop, so its scope starts with its declaration and continued to the end of the block.
Question 12:
Is the following code fragment correct?
int sum = 0;
for ( int j = 0; j < 8; j++ )
sum = sum + j;
System.out.println( "The sum is: " + sum );