aspose file tools*
The moose likes Beginning Java and the fly likes Need help to understand basic arithmetics in Java Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Need help to understand basic arithmetics in Java" Watch "Need help to understand basic arithmetics in Java" New topic
Author

Need help to understand basic arithmetics in Java

raul saini
Greenhorn

Joined: May 18, 2010
Posts: 18
Suppose we have this expression:



now i need to know how java performs this operation.
I know the precedence but still not able to figure out.

Please explain.
Thank You
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 10928
    
  12

you should probably read something like this. operators all have a precedence - some get done before others, just like in math.

If i recall correctly, anything inside parens is done first, so we'd get

6*10/5*5+14/2-9+20

Then, mult/div come next, in order from left to right

60/5*5+14/2-9+20

60/5*5+14/2-9+20

12*5+14/2-9+20

60+14/2-9+20

60+7-9+20

then, addition and subtraction, in order from left to right

67-9+20
58+ 20
78




There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
raul saini
Greenhorn

Joined: May 18, 2010
Posts: 18
Thank you very much, I was performing multiple calculation at a time.
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 10928
    
  12

well, you can, as long as you complete ALL operations of a given precedence before any others. I could have just as easily done this:

6*10/5*5+14/2-9+(10*2);

6*10/5*5+14/2-9+20; //take care of everything inside parens

60 + 7 - 9 + 20 // take care of all multiplication and division

78 // take care of all addition and subtraction.



Istvan Kovacs
Ranch Hand

Joined: May 06, 2010
Posts: 100
Note that with integer types, you can encounter issues due to losing data when performing calculations, which may make it seem that Java violates rules of arithmetics. For example:
(a / b * c) = (a * c / b) may not hold:

Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36598
    
  16
That problem with integer arithmetic applies to most computer languages.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19556
    
  16

With floating point calculations there can even be a difference between (a+b)+c and a+(b+c).


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
jQuery in Action, 2nd edition
 
subject: Need help to understand basic arithmetics in Java
 
Similar Threads
Finding the closet element to Zero in a Array
MyPattern.Java - homework help?
Backtracking recursion problems.
why to use conditional operator " ? " ?
C quiz questions