This week's book giveaway is in the Server-Side JavaScript and NodeJS forum.
We're giving away four copies of Micro Frontends in Action and have Michael Geers on-line!
See this thread for details.
Win a copy of Micro Frontends in Action this week in the Server-Side JavaScript and NodeJS forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

Exam Prep question re post increment

 
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
 
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
 
I'd appreciate it if you pronounced my name correctly. Pinhead, with a silent "H". Petite ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic