Math methods

In mathematics, you have probably seen functions like sin and log, Java provides functions that perform the most common mathematical operations. These functions are called methods. The math methods are invoked using a syntax that is similar to the print statements we have already seen:

  double root = Math.sqrt(17.0);
  double angle = 1.5;
  double height = Math.sin(angle);

The first example sets root to the square root of 17. The second example finds the sine of the value of angle, which is 1.5. Java assumes that the values you use with sin and the other trigonometric functions (cos, tan) are in radians. To convert from degrees to radians, you can divide by 360 and multiply by 2 PI. Conveniently, Java provides Math.PI:

  double degrees = 90;
  double angle = degrees * 2 * Math.PI / 360.0;

Notice that PI is in all capital letters. Java does not recognize Pi, pi, or pie.

Another useful method in the Math class is round, which rounds a floating-point value off to the nearest integer and returns an int.

  int x = Math.round(Math.PI * 20.0);

In this case the multiplication happens first, before the method is invoked. The result is 63 (rounded up from 62.8319).