• 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

Exam Prep question re post increment

 
Ranch Hand
Posts: 90
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In Dan Chisholm's Exam # 19, Question 21. I am trying to understand why the last value printed is a 3 instead of a 2. Here is the code:

public class JMM125 {

static int i;

public static void main(String[] args) {
for ( i = 1; i < 3; i++) {
System.out.println(i);}
for (int i = 1; i < 3; i++) {
System.out.println(i);}
int i;
for (i = 0; i < 2; i++) {
System.out.println(i);}
System.out.println(JMM125.i);
}

And here is the output:

1
2
1
2
0
1
3

Thank you for any enlightenment,

Sincerely,

JerryB
 
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In the very first for loop, you're modifying the static variable, i. You run through the loop when i = 0, 1, and 2. Then, you increment i to 3, the condition fails, and you exit the loop.

From then on, you are constantly referring to "local" i variables that shadow the static one so, at no point, does the static variable i change value - it remains at 3. Then, when you get to the final line, you spit out the value of the static variable i, which, of course, is 3.
 
Jerry Bustamente
Ranch Hand
Posts: 90
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Corey!

:-)

JerryB
reply
    Bookmark Topic Watch Topic
  • New Topic