Session 1 |
Class Math
The Java Math class contains many math functions. That means we do not have to create math methods on our own, but we can use the implemented ones (check the available methods here).
The methods usually take parameters and return values (generally, double type).
Some examples:
Syntax | Example | Summary |
double random() | double x = Math.random(); | returns a double value [0.0; 1.0) with a positive sign |
double abs(double x) | double x = Math.abs(-12.5); | returns the absolute value of a double value |
double floor(double x) | double x = Math.floor(4.2); | returns the closest to positive infinity double value that is less than or equal to the argument |
long round(double x) | long x = Math.round(0.66); | if a decimal is .5 or more round up to the next int; otherwise round down |
double ceil(double x) | double x = Math.ceil(4.2); | returns the closest to negative infinity double value that is greater or equal to the argument |
double sin(double radians) | double x = Math.sin(Math.PI / 2.0); | sine of the angle in radians |
Self-assessment
What is the output of the following program?
public class HelloWorld { public static void main(String[] args){ double rand_integer = Math.random()*5+15; long round_rand_num = Math.round(Math.random()*5+15); System.out.println(rand_integer); System.out.println(round_rand_num); } }
Run the code in IntelliJ and check your answer!
Session 1 |