Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!

# Does parenthesis makes difference on calculation?

Caglar Cataloglu
Greenhorn
Posts: 25
My problem is getting different results of a calculation with using parenthesis and without parenthesis.

When i run this line of code, i get the result as above.

Result is = 12345678987654321
But when i run this, i get a weird result.

Result is = 1653732529

I know that if you do not use casting to long type, you will loose some data because the operations on Java is calculated in integers, right?

Any idea what is going on here?

Henry Wong
author
Marshal
Posts: 21123
78
Caglar Cataloglu wrote:
I know that if you do not use casting to long type, you will loose some data because the operations on Java is calculated in integers, right?

Any idea what is going on here?

Exactly what you stated.

Henry

Henry Wong
author
Marshal
Posts: 21123
78
• 1

To give more details....

In the first example, the first int was converted to a long; a long is then multiplied with an int, yielding another long; and this long is then assigned.

In the second example, the two ints are multiplied. This multiplication yields an int which isn't big enough to hold the result. This result is then converted to a long and assigned.

Henry

Rob Spoor
Sheriff
Posts: 20531
54
• 1
Caglar Cataloglu wrote:

You're casting only int1 to long, then perform long * int calculation that returns a long.

You're performing int * int calculation that returns an int. You then cast this int to a long.

Caglar Cataloglu
Greenhorn
Posts: 25
Thank you Henry and Rob for clarifying this issue. Now i got the idea.

I have 1 more question.
Is it convenient to make more than 10 digit calculations using long data type via casting integers to long data types?

Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15284
39
Well, what exactly do you mean by "convenient"? If the numbers you are doing calculations with do not fit in a 32-bit int, then you need to use something else, such as a 64-bit long. It's not really a matter of convenience.