This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes can anyone tell me the correct answer for the following question with explanation 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 "can anyone tell me the correct answer for the following question with explanation" Watch "can anyone tell me the correct answer for the following question with explanation" New topic
Author

can anyone tell me the correct answer for the following question with explanation

R .sourav nayak
Ranch Hand

Joined: May 14, 2006
Posts: 67
class JMM125 {
static int i;
public static void main(String args[]) {
for (i=1; i<3; i++) {System.out.print(i);} // 1
for (int i=1; i<3; i++) {System.out.print(i);} // 2
int i; // 3
for (i=0; i<2; i++) {System.out.print(i);} // 4
System.out.print(JMM125.i);
}}

What is the result of attempting to compile and run the program?

a. Prints: 1212010
b. Prints: 1212013
c. Compile-time error at line 1
d. Compile-time error at line 2
e. Compile-time error at line 4
f. Run-time error
g. None of the above

why the correct answer is b. 1212013?

thanks in advance
reena
Radoslaw Sztando
Ranch Hand

Joined: Mar 11, 2004
Posts: 40
Hi,


first "for" loop is iterating using JMM125.i variable. It prints: "12" (and JMM125.i is set to 3).
Second loop uses loop-local variable and also prints "12". After loop finishes variable is disposed.
Third loop uses variable declared in line //3. It prints "01".
And last line prints value of JMM125.i which is set to 3 at first loop.

As a result 1212013 is printed.

Hope it helps


Regards,
Radek Sztando
nivas ratthaaq
Greenhorn

Joined: Aug 15, 2006
Posts: 18
Remember always local variable got preference over global varibales.When you say 'i' means it tries to access the local variable 'i' (if it is there!).
wise owen
Ranch Hand

Joined: Feb 02, 2006
Posts: 2023
What is variable hiding and shadowing?
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: can anyone tell me the correct answer for the following question with explanation
 
Similar Threads
Doubt in Declarations
Doubt in For loop
Variable scope confusion
Doubt in For Loop..
shadowing local variable