Math Class
This page was last reviewed on Jun 9, 2022.
Dot Net Perls
Math. In Java we use the Math class for high-quality mathematical methods. It computes simple things like absolute values, to complex ones like cube roots.
We access some constants like Math.PI directly on the Math type. And some methods like Math.addExact give us more control over arithmetic.
Math.E, PI. Sometimes programs need to use the E and pi constants. With the Math class, we can access these as fields. We do not need to specify 3.14 for pi.
Tip Using these included constants results in much clearer code—and no mistakes in the value of pi.
public class Program { public static void main(String[] args) { // Get these known constants. double value1 = Math.E; double value2 = Math.PI; System.out.println(value1); System.out.println(value2); } }
2.718281828459045 3.141592653589793
Exact methods. The Math class provides "exact" methods. These do what we expect (add, subtract, multiply) but throw an ArithmeticException when the result overflows.
So In a computation where overflow would be disastrous, these methods help check that the program is correct.
Part 1 Here we call the "exact" methods with 1 or 2 arguments. We store the results of the methods in locals.
Part 2 We display the results of all the method invocations. For the "addExact" method, 1 + 1 equals 2.
Part 3 We call multiplyExact with 2 arguments that will cause an overflow. An exception is thrown, and printed to the console.
import java.lang.Math; public class Program { public static void main(String[] args) { // Part 1: use exact methods. int result1 = Math.addExact(1, 1); int result2 = Math.addExact(100, 1); int result3 = Math.subtractExact(100, 1); int result4 = Math.multiplyExact(5, 4); int result5 = Math.incrementExact(2); int result6 = Math.decrementExact(1000); int result7 = Math.negateExact(100); // Part 2: display our results. System.out.println(result1 + " " + result2 + " " + result3 + " " + result4 + " " + result5 + " " + result6 + " " + result7); // Part 3: an ArithmeticException is thrown if a number overflows. try { int invalid = Math.multiplyExact(Integer.MAX_VALUE, 100); } catch (Exception ex) { System.out.println(ex); } } }
2 101 99 20 3 999 -100 java.lang.ArithmeticException: integer overflow
Math.toIntExact. The Math class has some conversion methods. Here, we use toIntExact, which converts along value to an int. The int must be able to store the long's value.
Detail The value 100 can be stored in an int, so the first toIntExact call succeeds. But Long.MAX_VALUE cannot be stored in an int.
import java.lang.Math; public class Program { public static void main(String[] args) { // An int can store the value 100. long test = 100; int result = Math.toIntExact(test); System.out.println("INT: " + result); // This will cause an exception, as the int cannot store the value. test = Long.MAX_VALUE; result = Math.toIntExact(test); } }
INT: 100 Exception in thread "main" java.lang.ArithmeticException: integer overflow at java.base/java.lang.Math.toIntExact(Math.java:1071) at Program.main(Program.java:13)
Abs. A number is -1. With the Math.abs method, we take its absolute value. So negative one is transformed into one. Positive numbers are left unchanged.
Floor. When we take the floor of a number we get the nearest, lower integral value. So the floor of 4.9 is 4. We can use Math.floor, floorDiv and floorMod.
Detail The ceiling of 4.1 is 5. With Math.ceil in Java we compute the ceiling function for floating-point numbers.
Square root. Imagine a square. It has an area. With the square root function, we map its area (a number) to the length of one of its sides.
Math.max, min. These methods receive two numeric arguments. Math.max returns the higher of the two arguments. And Math.min returns the lower one.
Math.max, Math.min
Math.pow. With this method we use exponents. We can square numbers by raising a number to the power of 2. The second argument to Math.pow is the exponent.
Random. We use the Math.random method to get a pseudo-random number. Internally this method creates a Random class instance. It makes using random numbers easier.
Math.round. With doubles and floats we have numbers like 10.5 and 10.9. Theses are often "rounded up" to 10. With Math.round we have an efficient way to round numbers.
Truncate. There is no Math.truncate method in Java 8. But we can create a truncate method that combines Math.ceil and Math.floor with good results for both positive and negative numbers.
Compound interest. We use Math.pow() to compute compound interest, which is an exponential function. Investment interest compounds at different rates (schedules).
A summary. With the Math class, we use declarative method calls to compute values. We avoid implementing this code ourselves—instead, we use built-in methods.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jun 9, 2022 (simplify).
© 2007-2024 Sam Allen.