Java Math log()

The Java Math log() method computes the natural logarithm (base e) of the specified value and returns it.

The syntax of the log() method is:

Math.log(double x)

Here, log() is a static method. Hence, we are calling the method directly using the class name Math.


log() Parameters

  • x - the value whose logarithm is to be computed

log() Return Values

  • returns the natural logarithm of x (i.e. ln a)
  • returns NaN if the argument is NaN or less than zero
  • returns positive infinity if the argument is positive infinity
  • returns negative infinity if the argument is zero

Example: Java Math.log()

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

    // compute log() for double value
    System.out.println(Math.log(9.0));       // 2.1972245773362196

    // compute log() for zero
    System.out.println(Math.log(0.0));       // -Infinity

    // compute log() for NaN
    double nanValue = Math.sqrt(-5.0);
    System.out.println(Math.log(nanValue));  // NaN

    // compute log() for infinity
    double infinity = Double.POSITIVE_INFINITY;
    System.out.println(Math.log(infinity));  // Infinity

    // compute log() for negative numbers
    System.out.println(Math.log(-9.0));      // NaN

  }
}

Recommended Tutorial