Basic math operators will only get you so far. There are a bunch more that you can use to do things with more advanced methods like algebra, trigonometry, statistics, calculus, and more in Java.
Working with Simple Methods
The most basic is working with numbers and rounding them. There are three ways to deal with a decimal value on a number.
The first is to just eliminate it entirely. This is called finding the number’s floor. Any decimal value is simply removed. Even if it is .99999.
The second is to take any decimal value and raise it up to the next whole number, called the number’s ceiling. Any decimal value will move the number to the next whole number. Even if it is .00001.
The last is to do traditional rounding. Anything .5 or higher moves up to the next whole number. Anything below .5 moves down.
To perform these actions, we need to call a method.
A method is a named section of code that we can execute just by calling the name (followed by a pair of parentheses).
Some methods return a value, like our rounding examples mentioned earlier. When a method returns a value, the value that is returned essentially replaces the name of the method when it is called.
In order for most methods to work though, you need to give it something to work with. We provide values to the method by placing them in the pair of parentheses that follows the method name.
The variable a is provided to the Math.ceil() method which then performs the ceiling method. It returns a value of 2.0, which replaces the method call. That value is then assigned to b.
You can put anything that evaluates to a required parameter in a method call, including mathematical operators or other variables. You can even call another method within a method call.
Multiparameter Methods
Illegal Value Types in Methods
Math Constants
There are special values that you can refer to by name in Java that represent special irrational numbers that are constant and never change. The most common is π and e.
These are presented by using the phrases Math.E and Math.PI.
Code Examples
The next page shows examples of basic math methods that you can use in your programs.
This code is also available in the following GitHub repo:
Common math methods