1.
2.
3.
What is variable "scope" and how does it apply to each kind of variable?
public class X {
private static int a = 10; //"static" or "class" variable
//with class scope. It exists
//the whole time the program is running
private int b; //"instance" variable with class scope
//It exists during the lifetime
//of the object which contains it
public X(int b) { // b is a "local" variable with
// block scope and goes away at the
this.b = b; // end of the constructor
}
public void changeB(int c) { //c and d are a "local" variables
//with block scope which "go away"
int d = 5; //at the end of the method
b = c; //Change value of "instance" variable b to c
b += d;
}
public void sillyChangeB(int c) {
int d = 5;
int b = c; //b is a "local" variable which "hides"
//the "instance" variable b so its
b += d; //value is NOT changed
}
public int getB() {
return b;
}
public static void main(String[] args) {
System.out.println("a = " + a); //a exists even when there a no
//X class objects and unlike instance
//variables the main method can access it
X myX = new X(5); //Creates a new X object referred to by myX
myX.changeB(3);
System.out.println(myX.getB());
myX.sillyChangeB(6);
System.out.println(myX.getB());
myX = new X(7); //Creates a new X object referred to by myX
//The garbage collector gets rid of the old one
myX = null; //Tells the garbage collector to pick up this
//object, too, because we don't need it anymore
}
}
/**PROGRAM OUTPUT:
csc% java X
a = 10
8
8
*/