Mathematical Operations and Functions

The Math class in Java’s java.lang package provides static methods and constants for mathematical operations.

Basic Math Operations

Trigonometric Operations

Exponential & Logarithmic Operations

Rounding & Precision Methods

Random Number Generation

Common Constants

Program

public class MathClassDemo {
    public static void main(String[] args) {
        System.out.println("Absolute Value: " + Math.abs(-10));
        System.out.println("Maximum Value: " + Math.max(10, 20));
        System.out.println("Minimum Value: " + Math.min(10, 20));
        System.out.println("Power: " + Math.pow(2, 3));
        System.out.println("Square Root: " + Math.sqrt(16));

        double radians = Math.toRadians(90);
        System.out.println("Sine of 90 degrees: " + Math.sin(radians));
        System.out.println("Cosine of 0 degrees: " + Math.cos(Math.toRadians(0)));
        System.out.println("Tangent of 45 degrees: " + Math.tan(Math.toRadians(45)));

        System.out.println("Exponential (e^1): " + Math.exp(1));
        System.out.println("Natural Log (ln(e)): " + Math.log(Math.E));
        System.out.println("Log base 10 (100): " + Math.log10(100));

        System.out.println("Ceiling of 4.2: " + Math.ceil(4.2));
        System.out.println("Floor of 4.9: " + Math.floor(4.9));
        System.out.println("Round 4.5 to long: " + Math.round(4.5));
        System.out.println("Round 4.5f to int: " + Math.round(4.5f));

        System.out.println("PI Value: " + Math.PI);
        System.out.println("E Value: " + Math.E);

        System.out.println("Random Value: " + Math.random());
    }
}
/*
Absolute Value: 10
Maximum Value: 20
Minimum Value: 10
Power: 8.0
Square Root: 4.0
Sine of 90 degrees: 1.0
Cosine of 0 degrees: 1.0
Tangent of 45 degrees: 0.9999999999999999
Exponential (e^1): 2.718281828459045
Natural Log (ln(e)): 1.0
Log base 10 (100): 2.0
Ceiling of 4.2: 5.0
Floor of 4.9: 4.0
Round 4.5 to long: 5
Round 4.5f to int: 5
PI Value: 3.141592653589793
E Value: 2.718281828459045
Random Value: 0.3745401188473625
*/

The java.lang.Math class provides a comprehensive set of static methods and constants to perform fundamental mathematical operations such as arithmetic calculations, trigonometry, logarithms, exponentials, rounding, and random number generation. It simplifies complex mathematical computations with optimized and reliable implementations. Since all methods are static, there is no need to create an instance of the class, making it convenient and efficient to use in any Java program.

Scroll to Top