Java Math tan()

The syntax of the tan() method is:

Math.tan(double angle)

Here, tan() is a static method. Hence, we are accessing the method using the class name, Math.


tan() Parameters

The tan() method takes a single parameter.

  • angle - angle whose trigonometric tangent is to be returned

Note: The value of the angle is in radians.


tan() Return Value

  • returns the trigonometric tangent of the specified angle
  • returns NaN if the specified angle is NaN or infinity

Note: If the argument is zero, then the result of the tan() method is also zero with the same sign as the argument.


Example 1: Java Math tan()

import java.lang.Math;

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

    // create variable in Degree
    double a = 30;
    double b = 45;

    // convert to radians
    a = Math.toRadians(a);
    b = Math.toRadians(b);

    // get the trigonometric tangent value
    System.out.println(Math.tan(a));   // 0.49999999999999994
    System.out.println(Math.tan(b));   // 0.7071067811865475

    // tan() with 0 as its argument
    System.out.println(Math.tan(0.0));  // 0.0
  }
}

In the above example, we have imported the java.lang.Math package. This is important if we want to use methods of the Math class. Notice the expression,

Math.tan(a)

Here, we have directly used the class name to call the method. It is because tan() is a static method.

Note: We have used the Java Math.toRadians() method to convert all the values into radians. It is because as per the official Java documentation, the tan() method takes the parameter as radians.


Example 2: Math tan() Returns NaN

import java.lang.Math;

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

    // create variable
    // square root of negative number
    // results in not a number (NaN)
    double a = Math.sqrt(-5);

    // Using Double to implement infinity
    double infinity = Double.POSITIVE_INFINITY;

    // print the tangent  value
    System.out.println(Math.tan(a));  // NaN
    System.out.println(Math.tan(infinity));  // NaN
  }
}

Here, we have created a variable named a.

  • Math.tan(a) - returns NaN because square root of a negative number (-5) is not a number

The Double.POSITIVE_INFINITY is a field of Double class. It is used to implement infinity in Java.

Note: We have used the Java Math.sqrt() method to compute the square root of a number.


Also Read:

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges