Java Math log() method with example

Last Updated : 21 Jan, 2026

The java.lang.Math.log() method returns the natural logarithm (base e) of a double value as a parameter. There are various cases :

  • If the argument is NaN or less than zero, then the result is NaN.
  • If the argument is positive infinity, then the result is positive infinity.
  • If the argument is positive zero or negative zero, then the result is negative infinity.

Syntax

public static double log(double a)

  • Parameter: "a" double value whose natural logarithm is to be calculated.
  • Return Type: Returns a double value representing ln(a) (natural logarithm of a).

Example 1: This program demonstrates how the Math.log() method behaves for different types of input values in Java.

java
class GFG {
    public static void main(String[] args) {
        double a = -2.55;
        double b = 1.0 / 0;
        double c = 0;
        double d = 145.256;
        System.out.println(Math.log(a));
        System.out.println(Math.log(b));
        System.out.println(Math.log(c));
        System.out.println(Math.log(d));
    }
}

Output
NaN
Infinity
-Infinity
4.978497702968366

Explanation:

  • Math.log(a) returns NaN because the logarithm of a negative number is undefined.
  • Math.log(b) returns Infinity since the input value is positive infinity.
  • Math.log(c) returns -Infinity because the logarithm of zero tends toward negative infinity.
  • Math.log(d) returns the natural logarithm (base e) of a positive number.

Example 2: This program shows how to compute the natural logarithm (base e) of a number using the Math.log() method in Java.

Java
import java.io.*;
class GFG {
    public static void main(String[] args)
    {
        double number = 10.0;
        double result = Math.log(number);
        System.out.println(result);
    }
}

Output
2.302585092994046

Explanation:

  • number stores the input value whose logarithm is to be calculated.
  • Math.log(number) computes the natural logarithm of 10.0.
  • The result is stored in result and printed to the console.
Comment
Article Tags: