Refer to the code segment below and answer the questions in the comments labelled Question 1 – 6 For each answer; provide a brief explanation for your answer. Each answered question earns you three (3) marks.
public class Scope
{
private int x = 2;
private int x = 1;
public void start()
{
int x = 5; int x = 2;
//Question 1
System.out.printf( "The value of x is %d\n", x );
int x = 2;
//Question 2
System.out.printf( "\nThe value of x is is % d\n", x ); }
// end method begin
public void middle()
{
int x = 25;
//Question 3
System.out.printf( "\nThe value of x is %d\n", x );
++x;
//Question 4
System.out.printf( "The value of x is %d\n", x );
} // end method middle
public void end()
{
//Question 5
System.out.printf(
"\nThe value of x is %d\n", x );
x *= 10;
//Question 6
System.out.printf( "The value of x is %d\n", x );
} // end method end } // end class Scope
class Scope
{
private int x = 2;
/*
We are commenting the second duplicate variable declaration, because java are not allow
to duplicate variable in the same scope, if we will not comment it, then it will show the error.
*/
//private int x = 1;
public void start()
{
int x = 5;
/*We are commenting the second duplicate variable declaration, because java are not allow
to duplicate variable in the same scope, if we will not comment it, then it will show the error. */
//int x = 2;
//Question 1
System.out.printf( "The value of x is %d\n", x ); // the value of x is 5
/*We are commenting the second duplicate variable declariation, because java are not allow
to duplicate variable in the same scope, if we will not comment it, then it will show the error. */
//int x = 2;
//Question 2
System.out.printf( "\nThe value of x is is % d\n", x ); // The value of x is 5
}
// end method begin
public void middle()
{
int x = 25;
//Question 3
System.out.printf( "\nThe value of x is %d\n", x ); // The value of x is 25 because middle method have x variable,
++x; // now x is increment by 1 x = 26
//Question 4
System.out.printf( "The value of x is %d\n", x ); // The value of x is 26
} // end method middle
public void end()
{
//Question 5
System.out.printf(
"\nThe value of x is %d\n", x ); // There end method haven't a x variable then it used class variable x, which have a x = 2, so The value of x is 2,
x *= 10; // value of x is now change after multiple by 10 it become x = 20
//Question 6
System.out.printf( "The value of x is %d\n", x ); // The value x is 20
} // end method end } // end class Scope
public static void main(String[] args) {
Scope obj = new Scope();
obj.start();
obj.middle();
obj.end();
}
}
Output:
Comments
Leave a comment