JAVA Math Class

JAVA Math class is a class that provides more advanced maths calculations than Java Math. It has direct methods for programs such as rounding off numbers, logarithmic algorithms, the factorial of a number, and concatenation of string, trigonometric functions, finding max and min of two numbers in the math package. Some of the useful methods are round(), fact(), min(), max(), avg(), sin(), cos(), tan(), ceil(), floor() etc.

All these methods are found in java.lang package and the math class not necessarily need to be imported. But we can use a static import in case of extensively using these functions. As a result, the code throws an Arithmetic exception when the range overflows.

For example, we take two integers and apply addExact() to add their value and the output doesnβt lie in the range of the value. It will throw an Arithmetic exception. For other such operations such as increment, subtraction, decrement, negation etc, the overflow will occur with a specific range of either minimum or maximum. The value needs to be checked properly before applying the math class method.

Here is how we declare the java.lang.Math class in Java:

``````public final class Maths
extends object``````

Math methods used in Java

Below is a program which states the uses of some math functions:

``````import java.math.*;
public class HelloWorld{

public static void main(String []args)
{
int ValueI = -10;
float ValueF = .10f;

System.out.println("Initial value of integer  : "+ValueI);
System.out.println("Initial value of integer F  : "+ValueF);

int AbsoluteI = Math.abs(ValueI);
float Absolutef = Math.abs(ValueF);

System.out.println("Absolute value of integer : "+AbsoluteI);
System.out.println("Absolute value of integer F : "+Absolutef);
System.out.println("");

double Acosi = Math.acos(30);
System.out.println("acos value of Acosi : "+Acosi);
double a = Math.PI;
double Acosj = Math.acos(a);
System.out.println("acos value of Acosj : "+Acosj);
}
}
``````

The output of this program will be:

``````Initial value of integer  : -10
Initial value of integer F  : 0.1
Absolute value of integer : 10
Absolute value of integer F : 0.1

acos value of Acosi : NaN
acos value of Acosj : 1.5159376794536454
``````

Discover Our Exciting Courses and Quiz

Enroll now to enhance your skills and knowledge!

Java Online Quiz

Level up your coding skills with our interactive programming quiz!