Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Exam Prep question re post increment Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Exam Prep question re post increment" Watch "Exam Prep question re post increment" New topic
Author

Exam Prep question re post increment

Jerry Bustamente
Ranch Hand

Joined: May 24, 2004
Posts: 90
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

Joined: Dec 20, 2001
Posts: 3271
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.


SCJP Tipline, etc.
Jerry Bustamente
Ranch Hand

Joined: May 24, 2004
Posts: 90
Thanks Corey!

:-)

JerryB
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Exam Prep question re post increment
 
Similar Threads
Shadowing Doubt again?
Doubt in For loop
Variable scope confusion
Doubt in For Loop..
shadowing local variable