• Post Reply Bookmark Topic Watch Topic
  • New Topic

Does parenthesis makes difference on calculation?  RSS feed

 
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
 
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!