File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Exam Prep question re post increment
 
Similar Threads
Doubt in For Loop..
Shadowing Doubt again?
shadowing local variable
Doubt in For loop
Variable scope confusion