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
4
5
4

C.
6
4
6
4

D.
6
4
4
4

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 2

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


Abed Abu Alhalawa

Abed Abu Alhalawa

A.
6
5
6
4

James

James

Answer is A.

The main(String args[]) and doStuff() methods declares a new local variable z. Only the doStuff2() method changes the public instance variable z, which is reflected in myScope.z.