Object Oriented Programming with Java

⌘K
  1. Home
  2. Docs
  3. Object Oriented Programmi...
  4. Essential Java Classes
  5. Math Class

Math Class

The Math class provides methods for performing mathematical operations like exponentiation, logarithms, square roots, trigonometry, and random generation.

Thank you for reading this post, don't forget to subscribe!
  • You don’t need to create an object of the Math class to use its methods.

Key Features:

  • All methods are static and can be accessed using Math.methodName().
  • It is used for basic and advanced mathematical operations.
  • It includes built-in constants for π (pi) and Euler’s number (e).
  • It is designed for double precision calculations.
  • It is useful in game development, scientific applications, finance calculations, etc.

Math Class Syntax:

  • The Math class is a part of the java.lang package.
Math.methodName(arguments);
  • final: Cannot be subclassed.
  • extends Object: Like all Java classes, it inherits from Object.
  • All methods in the Math class are static, so they can be called without creating an object.
Math Class

Random Number Generation:

  • Math.random() generates a double value greater than or equal to 0.0 and less than 1.0.

Example:

public class MathClassExample {
    public static void main(String[] args) {
        System.out.println("Square root of 16: " + Math.sqrt(16));
        System.out.println("2 raised to 3: " + Math.pow(2, 3));
        System.out.println("Absolute value of -10: " + Math.abs(-10));
        System.out.println("Round 5.6: " + Math.round(5.6));
        System.out.println("Ceil of 4.3: " + Math.ceil(4.3));
        System.out.println("Floor of 4.7: " + Math.floor(4.7));
        System.out.println("Maximum of 10 and 20: " + Math.max(10, 20));
        System.out.println("Random number: " + Math.random());
    }
}

How can we help?