*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Question on scope Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Question on scope" Watch "Question on scope" New topic
Author

Question on scope

Richard Huang
Greenhorn

Joined: Oct 02, 2000
Posts: 26
Can any one tell me why I can get these output in the cases listed below? thanks!
Case 1

Output:

x in the initializer: 5
x in the instance: 10

Case 2

Output:

x in the initializer: 5
x in the instance: 5

Case 3

Output:

x in the initializer: 5
x in the instance: 100

[This message has been edited by Richard Huang (edited October 03, 2000).]
[This message has been edited by Richard Huang (edited October 03, 2000).]
Harry Singh
Ranch Hand

Joined: Sep 22, 2000
Posts: 53
Hi Richard,
No matter what you do
"x in the initializer: 5" ---
will always be printed. This is because x is defined as a variable local to that block. It shodows any instance variables that have been defined for the class.
For the first case where you have
x in the instance: 10
Here the 'x' refereed to is the instance variable which you have initialized to 10. When this println is executed there is no other x existing in the class.
For the second case
There is no difference in the code between this case and the first.
For the third case...
Have a look at the code below. Run it and see the o/p. It will clear a lot of things for you...
class TestScope {
int x = 10;// First I do this
// Third I do this
TestScope()
{
System.out.println("x in the constructor before assignment: " + x);
x = 100;
System.out.println("x in the constructor after assignment: " + x);
}

// Second I do this
{
System.out.println("x in the initializer before assignment: " + x);
x = 5;
System.out.println("x in the initializer after assignment: " + x);
}
public static void main(String[] args) {
TestScope t = new TestScope();
System.out.println("x in the instance: " + t.x );
}
}

I have put comments to indicate the order of execution. Hope it helps.
Thanks,
Harry
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Question on scope