Parameter Practice

(taken from Stanford)

1. True/False questions

a. The value of a local variable named i has no direct relationship with that of a variable named i in its caller.

b.The value of a parameter named x has no direct relationship with that of a variable named x in its caller.

c.Assigning a new value to a parameter changes the value of the corresponding variable in the caller’s argument list.

d. Local variables of type int are automatically initialized to 0 when a method is called.

e. The return statement allows methods to return more than one value.

f. Predicate methods always return a value of the primitive type boolean.

 

2. It is not always easy to understand the relationships among variables in the different methods that make up a program. Suppose someone tells you that it would be easier if a particular variable name, such as total or i, always contained the same value in any part of the program in which that variable appeared. In your own words, describe what would be wrong with that approach?

 

3. Suppose that you wanted to explain the concept of arguments and parameters to someone with no background in programming at all. What everyday, real-world example would you use to make it clear why a procedure (or any generalized notion of a set of steps for carrying out a particular task) might want to include some form of parameterization?

 

4.In a few sentences, describe the difference between local variables and instance variables. Make sure that your answer includes any differences in (a) how those variables are declared and (b) how long the values of those variables persist.

 

5. Trace the execution of the following program

public class Hogwarts {
public void run() {
bludger(2001);
}
private void bludger(int y) {
int x = y / 1000;
int z = (x + y);
x = quaffle(z, y);
System.out.println("bludger: x = " + x + ", y = " + y + ", z = " + z);
}
private int quaffle(int x, int y) {
int z = snitch(x + y, y);
y /= z;
System.out.println("quaffle: x = " + x + ", y = " + y + ", z = " + z);
return z;
}
private int snitch(int x, int y) {
y = x / (x % 10);
System.out.println("snitch: x = " + x + ", y = " + y);
return y;
}
}