TheDeveloperBlog.com


Java

Java Math Class: java.lang.Math

Math. With arithmetic operators, we can compute any value. But this becomes complex, and in large programs, a heavy burden. With the Math class in Java, we use built-in methods.


Quality. The Math methods in this language are diverse. We compute simple things like absolute values, to complex ones like cube roots. These are tested, of high quality.


Absolute value. Let us start. An absolute value is the number with no negative sign. If the number is already positive, no change is made. We first import java.lang.Math.

Types: Math.abs returns various types. These depend on the types passed to it. If we pass an int, we receive an int in return.

Int
Based on:

Java 7

Java program that uses Math.abs

import java.lang.Math;

public class Program {
    public static void main(String[] args) {

	// This version uses an int.
	int value = Math.abs(-1);
	System.out.println(value);

	// This version uses a double.
	double value2 = Math.abs(-1.23);
	System.out.println(value2);

	int value3 = Math.abs(1);
	System.out.println(value3);
    }
}

Output

1
1.23
1

Floor. The floor is always beneath us. Likewise the Math.floor method always returns a lower integer. So 1.9 is lowered to 1, as is 1.1. For negative numbers, floor() still lowers.

Java program that uses Math.floor

import java.lang.Math;

public class Program {
    public static void main(String[] args) {

	// These are all reduced, even the negative number.
	double floor1 = Math.floor(1.9);
	double floor2 = Math.floor(1.1);
	double floor3 = Math.floor(-1.3);

	System.out.println(floor1);
	System.out.println(floor2);
	System.out.println(floor3);
    }
}

Output

1.0
1.0
-2.0

Ceiling. With this method, a number is always increased if it has a fractional part. It does not matter how close to the lower number the number is—it is increased by ceil().

Java program that uses Math.ceil

import java.lang.Math;

public class Program {
    public static void main(String[] args) {

	// Compute ceilings of these values.
	double value = Math.ceil(1.1);
	double value2 = Math.ceil(-0.9);

	System.out.println(value);
	System.out.println(value2);
    }
}

Output

2.0
-0.0

Square root. Consider this program—it does not import java.lang.Math at its top. Instead we directly access Math.sqrt using its composite name. We already know what sqrt does.

Java program that uses Math.sqrt

public class Program {
    public static void main(String[] args) {

	// ... Test the sqrt method.
	double value = java.lang.Math.sqrt(4);
	double value2 = java.lang.Math.sqrt(9);

	System.out.println(value);
	System.out.println(value2);
    }
}

Output

2.0
3.0

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.

Java program that gets Math.E, 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);
    }
}

Output

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.

Tip: An exception is easier to debug than an unusual result from a mathematical computation, which may just cause incorrect output.

Java program that uses addExact, exact methods

import java.lang.Math;

public class Program {
    public static void main(String[] args) {

	// 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);
	// Display our results.
	System.out.println(result1 + " " + result2 + " " + result3 + " "
		+ result4 + " " + result5 + " " + result6 + " " + result7);

	// An ArithmeticException is thrown if a number overflows.
	try {
	    int invalid = Math.multiplyExact(Integer.MAX_VALUE, 100);
	} catch (Exception ex) {
	    System.out.println(ex);
	}
    }
}

Output

2 101 99 20 3 999 -100
java.lang.ArithmeticException: integer overflow

Pow stands for power. If you have ever been in a math course, you already know what Math.pow does. It raises the first number to the power of the second number.

Compound interest: We use Math.pow() to compute compound interest, which is an exponential function.

Compound Interest
Java that uses Math.pow method

public class Program {
    public static void main(String[] args) {

	// Raise 5 to the power of 2.
	// ... Then raise 3 to the power of 2.
	double result1 = Math.pow(5, 2);
	double result2 = Math.pow(3, 2);
	// ... Display our results.
	System.out.println(result1);
	System.out.println(result2);
    }
}

Output

25.0
9.0

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.

Random

With abstraction, we conceal incredible levels of complexity. This is called information hiding. With the Math class, we use declarative method calls to compute values.


As developers, we can avoid implementing this code ourselves. Instead we use prebuilt, tested, optimized methods. In most cases (not all) this approach is best.