• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Rob Spoor
  • Bear Bibeault
Saloon Keepers:
  • Jesse Silverman
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • Al Hobbs
  • salvin francis

Wrong Output?

 
Ranch Hand
Posts: 435
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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..
 
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Ranch Hand
Posts: 252
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
reply
    Bookmark Topic Watch Topic
  • New Topic