michealAtmi
michealAtmi

Reputation: 1042

Java prefix and postfix operands

Am I thinking right? How to rewrite below to simple assigments to show how the operations are done?

int a = 3;
int b;

b = --a * --a;

Java does:

b = (a=a-1) * (a=a-1) = (2) * (1) = 1;

int a = 3;
int b;

b = a-- * a--;

Java does:

b = a; a=a-1;b=b*a;a=a-1;

b=3;a=3-1=2;b=3*2=6;a=2-1=1;

Upvotes: 0

Views: 123

Answers (2)

Joop Eggen
Joop Eggen

Reputation: 109557

    int a = 3;
    int b = --a * --a;
    System.out.println("pre " + b + "/" + a);

    a = 3;
    int r1 = a-1;   // 2
    a = r1;         // 2
    int r2 = a-1;   // 1
    a = r2;         // 1
    b = r1 * r2;    // 2
    System.out.println("pre2 " + b + "/" + a);


    a = 3;
    b = a-- * a--;
    System.out.println("post" + b + "/" + a);

    a = 3;
    r1 = a;         // 3
    a = r1 - 1;     // 2
    r2 = a;         // 2
    a = r2 - 1;     // 1
    b = r1 * r2;    // 6
    System.out.println("post2 " + b + "/" + a);

Where r1 and r2 are pushed / popped from the stack for multiplication.

Upvotes: 0

lriostavira
lriostavira

Reputation: 9

ok so in java the a--, first evaluates the a then it applies the operation (in this case subtraction),

for example:

   a=3;
   b=a--;

'b' will take the initial value of 'a' (b=3) and 'a' will then decrement (a=2).

In the following example:

    int a=3;
    int b;
    b= a-- * a--;
    System.out.println("a = " + a);
    System.out.println("b = " + b);

1. b=current value of a (3)
2. a=a-1 (2)
3. b=b * current value of a (b = 3 * 2)
4. a=a-1 (1)

And our result will be:

    b=6 a=1

for --a, java first applies the operation then it takes the value;

for example:

   a=3;
   b=--a;

'a' will decrement (a=2) and then 'b' will take the value of 'a' (b=2).

Example:

    int a=3;
    int b;
    b= --a * --a;
    System.out.println("a = " + a);
    System.out.println("b = " + b);

1. a=a-1 (2)
2. b=value of a (2)
3. a=a-1 (1)
3. b=b * value of a (b = 2 * 1)
And our result will be:

    b=2 a=1

hope this helps. good luck have fun :)

Upvotes: 1

Related Questions