Java Math sin()

The syntax of the sin() method is:

Math.sin(double angle)

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


sin() Parameters

The sin() method takes a single parameter.

  • angle - angle whose trigonometric sine is to be returned

Note: The value of the angle is in radians.


sin() Return Value

  • returns the trigonometric sine 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 sin() method is also zero with the same sign as the argument.


Example 1: Java Math sin()

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);

    // print the sine value
    System.out.println(Math.sin(a));   // 0.49999999999999994
    System.out.println(Math.sin(b));   // 0.7071067811865475

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

In the above example, we have imported the java.lang.Math package. It is a good practice to import the package. Notice the expression,

Math.sin(a)

Here, we have directly used the class name to call the method. It is because sin() 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 sin() method takes the parameter as radians.


Example 2: Math sin() 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 sine  value
    System.out.println(Math.sin(a));  // NaN
    System.out.println(Math.sin(infinity));  // NaN
  }
}

Here, we have created a variable named a.

  • Math.sin(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