Skip to content

Math

Math Methods

Math is defined in the java.lang package, as the name suggests math methods provide a wide variety of mathematical functions. The rules of Explicit and Implicit casting should be adhered to when returning values of the same type. Some examples of casting and when to consider them.

int result = Math.ceil(1.1F);
// Here we have a ceiling function for the float of 1.1
// As the ceiling function only returns a double or an int
// we need to ensure we cast our ceil to an int prior to return
int result = (int)Math.ceil(1.1F);
// This will now return a 2

Compilation errors can be easily avoided with the correct types being explicitly cast, it is important to note method returns when working with Math functions.

22.9910100190
double result = Math.random() * 100;
double result = Math.round(Math.random() * 100);
// Here, Math.round() rounds the random number to the nearest long value, and the result is stored in a double. Example: 22.0
int result = Math.round(Math.random() * 100);
// This will result in a compilation error because Math.round() returns a long, but we are trying to store it in an int. A cast is needed.
int result = (int) Math.round(Math.random() * 100);
// An additional explicit cast allows for us to now return an int as random number
// this will return 22 (random number between 1-100)
int result = (int) Math.random() * 100;
// This is an interesting example and will return 0
// our explicit casting is being applied to the Math.random() method call not to the formula
// Math.random returns a value between 0 and 1 thus being cast as an integer will result in 0
int result = (int) (Math.random() * 100);
// This would be the correct method to return an integer between 0 and 100