It's not a secret anymore!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Wrong Output? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Wrong Output?" Watch "Wrong Output?" New topic
Author

Wrong Output?

sonir shah
Ranch Hand

Joined: Nov 01, 2001
Posts: 435

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

Joined: Nov 14, 2001
Posts: 60
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

Joined: Jan 08, 2002
Posts: 54
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!


help you means help me
Seany Iris
Ranch Hand

Joined: Jan 08, 2002
Posts: 54
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

Joined: Nov 22, 2001
Posts: 249
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.
 
subject: Wrong Output?
 
Similar Threads
how to compare the values in arrays
Increment example
Please explain
Mock exam question
Speedway Trials