• 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:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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

 
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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!).
 
Ranch Hand
Posts: 2023
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What is variable hiding and shadowing?
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic