This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exam Prep question re post increment

 
Jerry Bustamente
Ranch Hand
Posts: 90
  • Mark post as helpful
  • send pies
  • 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
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • 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
  • Quote
  • Report post to moderator
Thanks Corey!

:-)

JerryB
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic