# Just a Simple Java Question

Greenhorn
Posts: 6
Hi there,

I'm just learning Java and playing around this simple code (it sums up the total of numbers in a range)

It prints sum of 1 to 10. But I don't quite understand the logic in the sum().

If, sum = sum + i;

How does it arrive at the calculation?

sum was initially 0 and i = x = 1 from the above

initially: sum = sum + 1
x = 1
level 1: 0 = 0 + 1 - initial state, so sum gets to be 1

x = 2
1 = 1 + 2 (1 increments to become 2), so sum gets to be 3 and so on.

This is the logic I'm trying to understand.

Can someone please shed more light on this for me or give it a better explanation.

Thank you.

Winston Gutkowski
Bartender
Posts: 10422
63
• 1
x = 2
1 = 1 + 2 (1 increments to become 2), so sum gets to be 3 and so on.

This is the logic I'm trying to understand.

Can someone please shed more light on this for me or give it a better explanation.

I'm not quite sure what it is you're having problems with because, apart from the fact that it's i that gets incremented, not x, your description seems to be right on the mark.

If need be, just continue the process until i == 10 and work out what sum should contain.

Winston

Joanne Neal
Rancher
Posts: 3742
16
• 1
Kareem Adams wrote:This is the logic I'm trying to understand.

Can someone please shed more light on this for me or give it a better explanation.

You seem to have explained it perfectly. What exactly about your explanation don't you understand ?

Greenhorn
Posts: 6
Thanks to you guys, here's what I did.

Doing it manually makes me understand maybe a little (technically).

But the part I really want to get right is in simple English.

How does that part work?

Because what it does is : 1+2+3+4+5+6+7+8+9+10

If I get this right, I'll be able to right something similar with better understanding without looking at any book.
The code I sent earlier was from a book I'm using to study.

And thanks to Matthew for formatting my code earlier.

I appreciate y'all effort.

Winston Gutkowski
Bartender
Posts: 10422
63
• 1
Kareem Adams wrote:But the part I really want to get right is in simple English.

How does that part work?

It works because ints in Java are modifiable, so the statement says:
take the value of sum, add i to it, and then use that result to modify sum.

Everything on the right-hand side of the '=' sign is based on the old value of sum, but after the statement has completed, sum will be updated with the new value.

In some languages (eg, C/C++) these are called 'lvalue's and 'rvalue's ('l' and 'r' being short for 'left' and 'right').

HIH

Winston

Greenhorn
Posts: 6
take the value of sum, add i to it, and then use that result to modify sum.

Everything on the right-hand side of the '=' sign is based on the old value of sum, but after the statement has completed, sum will be updated with the new value.

This explains it better.

Thanks Winston.