What is the result?

Given:
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;
}
}
What is the result?

Given:
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;
}
}
What is the result?

A.
6 5 6 4

B.
6 5 5 4

C.
6 5 6 6

D.
6 5 6 5

Explanation:
Within main z is assigned 6. z is printed. Output: 6
Within doStuff z is assigned 5.DoStuff2 locally sets z to 4 (but MyScope.z is set to 4), but in
Dostuff z is still 5. z is printed. Output: 5
Again z is printed within main (with local z set to 6). Output: 6
Finally MyScope.z is printed. MyScope.z has been set to 4 within doStuff2(). Output: 4



Leave a Reply 0

Your email address will not be published. Required fields are marked *