Description

On this document we will be showing a java example on how to use the tan(double a) method of Math Class. The tan(double a) returns the trigonometric tangent of the method argument value. It must be noted that the parameter is in radians, however if your source value is in degree which is always the case for real world applications the handy Math.toRadians() method will be helpful on the conversion. The following rule must be noted:

  • If the argument is NaN or an infinity, then the result is NaN.
  • If the argument is zero, then the result is a zero with the same sign as the argument.

Most of the methods of the Math class is static and the tan() method is no exception. Thus don’t forget that in order to call this method, you don’t have to create a new object instead call it using Math.tan(a).

Method Syntax

public static double tan(double a)

Method Argument

Data Type Parameter Description
double a an angle, in radians.

Method Returns

The Math.tan() method returns the trigonometric tangent of the argument.

Compatibility

Requires Java 1.0 and up

Java Math tan() Example

Below is a java code demonstrates the use of tan() method of Math class. The example presented might be simple however it shows the behaviour of the tan() method.

package com.javatutorialhq.java.examples;

import java.util.Scanner;

/*
 * This example source code demonstrates the use of  
 * tan() method of Math class
 */

public class MathTangentExample {

	public static void main(String[] args) {

		// Ask for user input
		System.out.print("Enter an angle in degrees:");

		// use scanner to read the console input
		Scanner scan = new Scanner(System.in);

		// Assign the user to String variable
		String s = scan.nextLine();

		// close the scanner object
		scan.close();

		// convert the string input to double
		double value = Double.parseDouble(s);
		// convert the value to radians
		double valueRadians = Math.toRadians(value);

		// get the tangent of the angle
		double tangentValue = Math.tan(valueRadians);
		System.out.println("Tangent of " + s + " is " + tangentValue);

	}

}

The above java example source code demonstrates the use of tan() method of Math class. We simply ask for user input and we use the Scanner class to parse it. Since we have used the nextLine() method to get the console value, and the return data type is String thus we have used the Double.parseDouble() to transform it into double. We have to convert it first to double because the tan() method accepts double method argument. After transforming into double we have also used Math.toRadians() to convert the degree input to radians which is the required method argument.

Sample Output

Below is the sample output when you run the above example.

java lang Math tan() example output