Multiple choice

What is the output of the given program code?

public class ScopeTest
{
int z;
public static void main(String[] args)
{
ScopeTest myScope = new ScopeTest();
int z = 6;
System.out.println(myScope.z);
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;
}
}

  1. Garbage value 6 5 6 4

  2. 6 6 5 6 4

  3. 0 6 5 6 4

  4. Compilation error

  5. Run time error

Reveal answer Fill a bubble to check yourself
C Correct answer
Explanation

This is the correct choice. Firstly, myscope.z will be printed, but it has not been initialised to any value. Initially it has a default value 0. So, 0 gets printed. Within main program, z is assigned the value 6. So, z = 6 is printed first. 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. So, z = 5 is printed. Again z is printed within main (with local z set to 6). Then z = 6 is again printed and finally MyScope.z is printed. MyScope.z has been set to 4 within doStuff2(). So, z = 4 gets printed. So, the correct output is 6 5 6 4. This is the correct choice.