Given the following program, what is the output? It must be in the correct order
ID: 639473 • Letter: G
Question
Given the following program, what is the output? It must be in the correct order! Figure it out by hand rather than by coding it!
public class Scope {
int x = 1;
static int y = 2;
public Scope() {
int x = 5;
System.out.println("x in Scope(1): " + x);
a();
b();
a();
b();
System.out.println("x in Scope(2): " + x);
}
void a() {
int x = 25;
System.out.println("x in a(1): " + x);
++x;
System.out.println("x in a(2): " + x);
}
void b() {
System.out.println("x in b(1): " + x);
x *= 10;
System.out.println("x in b(2) " + x);
}
public static void main(String[] args) {
Scope s = new Scope();
System.out.println("y in main(1) " + y);
System.out.println("y in main(2) " + s.y); }
}
------------------------ OUTPUT --------------------------------
Explanation / Answer
x in Scope(1): 5 //constructor of the scope is called
x in a(1): 25 // inside a() method ,local variable got the highest priority so x =25
x in a(2): 26 // inside a() method, increase the x by preincrement operator "++x" so x=26
x in b(1): 1 // inside b() method , it is using the instance variable x so value will be 1
x in b(2) 10 // inside b() method, multiplying x with 10 so value will be 10
x in a(1): 25 // inside a() method // inside a method ,local variable got the highest priority so x =25
x in a(2): 26 // inside a() method, increase the x by preincrement operator "++x" so x=26
x in b(1): 10 // inside b() method ,it is using the instance variable...previously the value was 10 so the present value will be 10
x in b(2) 100 // inside b() method,multiplying with 10 so value will be 100
x in Scope(2): 5 //inside class a, sysout will be called
y in main(1) 2 //main() method, main method sysout will be called
y in main(2) 2 //main() method,main method sysout will be called
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.