1
public class Latihan
{
    public static void main(String[] args)
    {
        int a = 0;
        System.out.println(++a + ++a * ++a);
    }
}

The output is 7. What is happening here? Please explain me. I'm still a newbie in programming.

7
  • 2
    What do you think it should be and why? Sep 15, 2014 at 1:29
  • 11
    so you think 1 + 2 * 3 is not 7?
    – Baby
    Sep 15, 2014 at 1:31
  • So, it does the increment first? Sep 15, 2014 at 1:32
  • 3
    Yes, because it's pre-increment.
    – lxcky
    Sep 15, 2014 at 1:32
  • 1
    This is a legitimate question to ask, but if you're new to programming, I'd also like to point out that you should avoid using this sort of construct (multiple pre-increments on the same variable in the same expression) at all cost (even when you are more experienced). This just makes the code confusing for everyone (and this behaviour wouldn't necessarily be the same in other languages). (... cont'd ...)
    – Bruno
    Sep 15, 2014 at 1:45

2 Answers 2

10

This is what happened:

++a + ++a * ++a
  1 +   2 *   3
  1 + 6
  7

EDIT 2

++a + a++ * ++a
  1 + 1   *   3
  1 + 3
  4
  • ++a means increment the value of a before using it, thus the pre-increment
  • a++ means use the value of a then increment it, thus the post-increment

Read more about operator precedence here.

2
  • Thank you. So it does the increment first? I thought it does the multiplication first. Sep 15, 2014 at 1:33
  • @ThoyibAntarnusa Yes, it does the increment first. I provided a link for the operator precedence in my answer. You can check that out for more information. :)
    – lxcky
    Sep 15, 2014 at 1:33
1

++a means "increment the value of a, returning the new (incremented) value". So, yes, the increment occurs before you have the value available to work with.

If that isn't what you wanted...

a++ means "increment the value of a, returning the previous (un-incremented) value".

int a=0;
System.out.println(++a); /* will print 1, and leave a set to 1 */
a=0;
System.out.println(a++); /* will print 0, and leave a set to 1 */

Similarly for the '--a' and 'a--' (decrement) operators.

Java expressions don't get quite as hairy as C expressions could, since Java doesn't have pointer manipulation operators, but there are still enough operators to make precedence confusing at times. That's especially true when side-effects are involved, as in this case. When in doubt -- or when you think the next person to read the code might be in doubt -- you may want to pull the increment out of the expression and perform it separately.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.