Multiple choice

What is the output of the given program?

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;
}
}

  1. 6 5 6 4

  2. 6 5 5 4

  3. 6 5 6 6

  4. Run time error

  5. Compilation fails

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

Within main program, z is assigned 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). So, z = 6 is again printed and finally myScope.z is printed.