Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Wrong Output?

 
sonir shah
Ranch Hand
Posts: 435
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Options :
1)The x value is 20
2)The x value is 30
3)The x value is 400
4)The x value is 600
Ans : 1)The x value is 20
I feel that the ans is 3)The x value is 400, Because in the method, y is 20 and 20*20 will give 400
Please explain me..
 
Arsho, Ayan
Ranch Hand
Posts: 60
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Sonir :
The main method just cannot access instance variable without creating an instance.The only 'x' variable accessible is local variable. so it prints 20.
Hope that helps!!
-A
 
Seany Iris
Ranch Hand
Posts: 54
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I know the X value only changed in the Method,But don't how to change the X value out the method. Who can explain it ,thanks!
 
Seany Iris
Ranch Hand
Posts: 54
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Arsho, Ayan:
Hi Sonir :
The main method just cannot access instance variable without creating an instance.The only 'x' variable accessible is local variable. so it prints 20.
Hope that helps!!
-A

I think this sentence "MyTest ta = new MyTest();" creating an instance, doesn't it?
 
Bhushan Jawle
Ranch Hand
Posts: 249
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Sonir,
There are three variables named 'x' in the example and all three have a different scope.
int x = 30; is associated with each instance but is out of scope as main() is a static method.
Line int x = y*y; in method 'Method()' defines another variable 'x' whose scope is limited to to braces of method 'Method()'.
When the code tries to print value of 'x' the only x it can see (or is accessible) is the one initialised as int x = 20 and hence the answer.
Rgds.,
Bhushan
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic