• 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

Variable scope confusion

 
Ranch Hand
Posts: 48
  • 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);
}}
For the above code why would the value of variable i increase to 3 and would not be 0? The answer to the above question is 1212013 and not 1212010
 
Ranch Hand
Posts: 330
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The last System.out.println refers to the static member variable i which was left with the value of 3 when the first for statement terminated. See code below.
 
brevity is the soul of wit - shakepeare. Tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic