3) Refer to the code segment below and answer the questions in the comments labelled Question i – vi. For each answer; provide a brief explanation for your answer.
public class Scope {
private int x = 2;
private int x = 1;
public void start() {
int x = 5;
int x = 2;
//Question i
System.out.printf( "The value of x is %d\n", x );
int x = 2;
//Question ii
System.out.printf( "\nThe value of x is is %d\n", x );
} // end method begin
public void middle() {
int x = 25;
//Question iii
System.out.printf( "\nThe value of x is %d\n", x );
++x;
//Question iv
System.out.printf( "The value of x is %d\n", x );
} // end method middle
public void end() {
//Question v
System.out.printf( "\nThe value of x is %d\n", x );
x *= 10;
//Question vi
System.out.printf( "The value of x is %d\n", x );
} // end method end
} // end class Scope
public class Scope {
private int x = 2;
private int y = 1;// should rename this variable because this non be compiled
public void start() {
int x = 5;
int y = 2;
// Question i
// This method if invoke will print x values only in parentheses
System.out.printf("The value of x is %d\n", x);
System.out.printf("The value of x is %d\n", y);
int z = 2;
// Question ii Name value x change to z because didn't compile
System.out.printf("\nThe value of x is is %d\n", z);
} // end method begin
public void middle() {
int x = 25;
//Question iii Will print 25 only in parentheses
System.out.printf("\nThe value of x is %d\n", x);
++x;
//Question iv Will print 26 after incrementing only in parentheses
System.out.printf("The value of x is %d\n", x);
} // end method middle
public void end() {
//Question v This method first of all will print private x and value 2 declared in top because didn't have local x in parentheses
System.out.printf("\nThe value of x is %d\n", x);
x *= 10;
//Question vi This method will print private x and value 20 multiply 2 by 10 because didn't have local x in parentheses
System.out.printf("The value of x is %d\n", x);
} // end method end
//add method main for invoke those methods
public static void main(String[] arg) {
Scope scope = new Scope();
scope.start();
scope.middle();
scope.end();
}
}
Comments
Leave a comment