I am very new to Java (4 weeks, 4 days a week), with zero prior programming knowledge. Can someone explain how this prints 32?
int a = 10;
a = a++ + a + a-- - a-- + ++a;
System.out.println(a);
I am very new to Java (4 weeks, 4 days a week), with zero prior programming knowledge. Can someone explain how this prints 32?
int a = 10;
a = a++ + a + a-- - a-- + ++a;
System.out.println(a);
a++ > means use then change .. So value of a is used first = 10 and then incremented = 11
++a > means change then use. So value of a is first changed then used.
So a = a++ + a + a-- - a-- + ++a;
= (10)
+ (11 [since a is incremented after use])
+ 11 [since a-- = use then change = 11, after -- becomes 10]
- 10 [since value of a is now decremented, and then decremented again, so a = 9 at this point]
+ 10 [since ++a is change then use]
in summary
a = 10 + 11 + 11 - 10 + 10 = 32.
Hope it helps :)
Easy:
a = 10 + 11 + 11 - 10 + 10 = 32.
It's clearer with parentheses added:
a = (a++) + (a) + (a--) - (a--) + (++a);
Let's take this one step at a time.
a++
will increment a by one.a++ +a
will take the (11)+ the existing a(10), to give 21- a--
will subtract 1 from a, and subtract this from the value. So -9, a
is incremented before any other operation starts. So a becomes 11, before everything else even calculates.Bottom line, this simplifies to:
4*a-a-2+1
= 3*a-1
, where a=11 because it has been incremented before anything started (++a).
If instead you moved the ++ to the other side of the ++a
, you'd have 29, which is much easier to understand where it comes from.
The ++ and -- are evaluated based on where they are in relation to the variable, if it is a++ then a is first evaluated, then it is incremented. If you have ++a, then a is incremented and then evaluated.
So a++ + b will take a and add it to be, and then increment it, while, ++a + b will first increment a, and then add it to b.
In simple
public static int i = 10;
is indicating that the integer i has a value of 10.
then saying
i++;
will make i's value 11, so it just like saying 10 + 1
saying
i--;
will makes i's value 9, so its like saying 10 - 1.
then
i = i + 1;
will do the same as i++;
but its used like i = i + 20;
in most cases to take its value and add 20 to it.
same for
i = i - 20;
but taking away instead of adding.
then
a + a;
that will double a.
Hope this helps, Luke.