Dusk
Dusk

Reputation: 2201

Arithmetic operator confusion

Why I'm getting two different values while using the arithmetic operators for the same value of variables. I've just altered little bit my second program, which is resulted in giving me the different output. Could anyone please tell me why?

    int number=113;
 int rot=0;
 rot=number%10;
 rot*=100+number/10;
 System.out.println(rot);//333



    int number=113;
 int rot=0;
 rot=number%10;
 rot=rot*100+number/10;
 System.out.println(rot);//311

Upvotes: 2

Views: 218

Answers (4)

Edan Maor
Edan Maor

Reputation: 10052

It seems like the problem is operator precedence.

What this means is that num * 10 + 13 is treated like (num * 10) + 13, i.e. the () are automatically added according to the rules of the language.

The difference then, in your example, is that the first one means the following:

rot*=100+number/10;
// Is the same as this:
rot = rot * (100 + (number / 10));

Whereas the second one means the following:

rot=rot*100+number/10;
// Is the same as this:
rot = (rot * 100) + (number / 10);

Since the parenthesis are in different places, these probably evaluate to different numbers.

Upvotes: 1

GuruKulki
GuruKulki

Reputation: 26418

in the second code because of the high precedence of *. rot*100 will be calculated and to that (number/10) will be added so its (300 + 11 = 311).

Upvotes: 0

jk.
jk.

Reputation: 13984

the problem is that *= has different (lower) precedence than * and +

rot *= 100 + number/10;

is equavalent to

rot = rot * (100 + number /10);

operator precdence can be found here

Upvotes: 2

Felix Kling
Felix Kling

Reputation: 816242

In the first part you compute

rot *= 100 + number/10

which is

rot = rot * (100 + number/10)

And in the second part:

rot = rot*100 + number/10

Note that multiplication and division goes before addition and substraction.

Upvotes: 8

Related Questions