How to Do Arithmetic in Java

Doing Programming Math in Java

Cloudage
Java makes it very simple to do arithmetic. This article will tell you exactly how easy it is to do addition, subtraction, multiplication and addition in Java!

I previously wrote about my fictional goldfish business. I declared a statement on how many goldfish I currently have, and how many got sold that day. I want to alter that statement to get the following code:

int yesterdayGFish = 400, numberSold = 30, numberGFish;

There are three integer variables, one for how many fish I had yesterday, one for how many got sold, and one for how many I have left. All of these variables share the same data type, otherwise we would have to break them down into separate statements. What we want to do now, is to find out how many goldfish I have left. I can write the following statement showing simple subtraction:

numberGFish = yesterdayGFish - numberSold ;

Since I have already declared the variables as data type int, I do not have to include "int" in the statement. I could also have written the statement as this:

numberGFish = 400 - 30 ;

I do like to work with variables however, as it makes the code much more readable.

Now numberGFish has the value 370 assigned to it. We can change it if we want to, as long as the data type is integer. If we forgot how many fish we had yesterday, and we were too lazy to look at the code, we could write:

yesterdayGFish = numberGFish + numberSold ;

We would then get the original 400 goldfish, because numberGFish is now 370!

Since I like to keep very good statistics, I also want to know what percentage of the fish that got sold. I declare another variable percentSold, and change the variable types to float since we'll be dealing with decimal numbers. There are other ways to do this without declaring all the variables as float, but to keep it simple we'll do this.

float yesterdayGFish = 400, numberSold = 30, numberGFish, percentSold;

To get the percent we have to divide the number of fish that got sold, with yesterday's stock, and then multiply with 100.

percentSold = (numberSold/yesterdayGFish)*100;

Doing arithmetic in Java is really this simple. You must know what data type you'll be dealing with, give the variables appropriate and easy-to-understand names, and then use the variables to add, subtract, multiply, or divide. Often the hardest part is knowing which data type to use, but besides that, Java makes it very simple to do easy math.

Published by Cloudage

I am a student studying and tutoring in math, chemistry and physics.  View profile

To comment, please sign in to your Yahoo! account, or sign up for a new account.