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:
Sheriffs:
Saloon Keepers:
Bartenders:

# Java "math" ?

Greenhorn
Posts: 7
Sorry this may seem like a really dumb question but could someone explain to me how this works:

This is the code example I wrote from the book I'm studying:

The code out put is:

Before the Loop
In the Loop
Value of x is 1
In the Loop
Value of x is 2
In the Loop
Value of x is 3
This is after the loop

Now I understand where the 1 comes from but I don't understand where the 2 and 3 come from. The answer is probably so simple I'm missing it.
Add code tags. CR[/edit]
[ November 27, 2008: Message edited by: Campbell Ritchie ]

Bartender
Posts: 11445
18

Originally posted by Paul Maxfield:
.. but I don't understand where the 2 and 3 come from. The answer is probably so simple I'm missing it.

It is because of this line

As you know, while loops will continue iterating as long as the condition specified evaluates to true (x<4) in your case.
So for the first iteration you get
x=1 so x<4 is true
For the second you get (since you are incrementing x's value by 1)
x=2 so x<4 is true
For the third you get
x=3 so x<4 is true
After that x becomes 4 and x<4 is false. So the control exits the while loop and you get the "This is after the loop".

Sorry this may seem like a really dumb question

Don't worry about this. I still confuse the pre-increment and post-increment operators sometimes
[ November 26, 2008: Message edited by: Maneesh Godbole ]

Marshal
Posts: 58295
178

Originally posted by Paul Maxfield:
Sorry this may seem like a really dumb question . . .

I trust Maneesh's explanation is satisfactory?

That is not a dumb question at all.

Ranch Hand
Posts: 378
Paul,
As you said, where does the 1 come from?

Maneesh Godbole
Bartender
Posts: 11445
18

Originally posted by Gamini Sirisena:
Paul,
As you said, where does the 1 come from?

From here

Paul Maxfield
Greenhorn
Posts: 7
Ah....now I get it, thank you very much

 It is sorta covered in the JavaRanch Style Guide.