-1

Could you help me a little bit? First of all, this is the code:

package helloworldapp;

public class HelloWorldApp
{
    public static void main(String[] args)
    {

        int jaja = 1;

        jaja = (jaja++)*2*2;

        System.out.println(jaja);
    }
}

I would like to understand this line:

jaja = (jaja++)*2*2;

As far as I know, postfix increment operator evaluates to the variable after the statement is done. Why does it give 4 as a result? Maybe I shouldn't use the same variable this way but I'm curious about that how it works. I thought that, firstly it multiply 'jaja' by 2, repeat it, the statement is over, and then add 1 to jaja. It would be 5 but I misunderstand something.

Um, it is my first comment here and also my English is really bad. Please forgive me for this :)

DoWhileFor
  • 35
  • 4
  • Postfix operator means *First use then increment*. – Braj May 22 '14 at 15:59
  • Yes, it is my problem. I thought that it first do the multiplications with the original value then it increments 'jaja' with 1. I don't understand why it doesn't give 5 as result. Please explain it somehow else. I'm just a beginner. – DoWhileFor May 22 '14 at 16:02
  • With postfix, use the value first. So the calculation is 1 * 2 * 2. Next, jaja is incremented to 2. Finally, jaja is set to 4. – Edwin Torres May 22 '14 at 16:05
  • Try `jaja += (jaja*2*2);` that will give you 5. – Braj May 22 '14 at 16:08

1 Answers1

0

Yes, jaja++ will increment jaja to 2, but the result of that expression is still 1, and *2*2 will yield 4, which is assigned to jaja, overwriting the 2.

rgettman
  • 176,041
  • 30
  • 275
  • 357
  • I think that is my problem. I thought that the incrementation would have done after the assignment. Thanks for all of your helps. Um, sorry for the duplication. I'm still not used to the proper forum use (but I will get used to it). – DoWhileFor May 22 '14 at 16:22