I am super new to programming and I'm studying for a test and don't understand the output of a piece of code. I was hoping you could help me understand why the 4 is being printed at the end?
I threw the code in the Java visualizer site and I understand everything except why the line... System.out.println(myScope.z); would print the number 4?
Any help is greatly appreciated!
public class ScopeTest {
int z;
public static void main(String[] args){
ScopeTest myScope = new ScopeTest();
int z = 6;
System.out.println(z);
myScope.doStuff();
System.out.println(z);
System.out.println(myScope.z);
}
void doStuff() {
int z = 5;
doStuff2();
System.out.println(z);
}
void doStuff2() {
z=4;
}
}
Stepping through code one line at a time is a good exercise to figure out what it is doing. You should do this with paper and pencil as well as with a debugger. So let's step through your code one line at a time in the order of execution. After each line of code, I'll explain what it does.
ScopeTest myScope = new ScopeTest();
Create a local reference variable named myScope
and initialize it to an object.
int z = 6;
Create a local int
variable named z
and initialize it to 6
.
System.out.println(z);
Print the value of the local variable z
.
myScope.doStuff();
Call doStuff()
on the myScope
object.
int z = 5;
Create a local variable z
in doStuff()
and initialize it to 5
.
doStuff2();
Call doStuff2()
z=4;
Set the member field named z
to the value 4
. And then return control back to doStuff()
.
System.out.println(z);
Print out the value of the local variable z
. And then return control back to main()
.
System.out.println(z);
Print out the value of the local variable z
. (Remember we are back in main()
now.
System.out.println(myScope.z);
Finally, print out the member field z
. (Remember its value was set back in doStuff2()
. This value is remembered because this z
is a member variable.)