Math Class
Math Class
Math Class
What is the Math Class?
The Math Class is another class that is
prepared by Java for us to use
Import Java.util.*;
It is automatically imported
How to use the Math Class
You must include the class name Math
each time you wish to use the Math Class
Example;
System.out.println(Math.pow(2,8));
Why? 28 = 256
System.out.println(Math.pow(2,8));
Problem?
By using the code above the result of 256
is not being saved anywhere as it is just
simply an output
System.out.println(result);
Fed up of writing Math …
Programmers are lazy and do not enjoy
writing the same things a number of times
import static.java.lang.Math.*;
…
Once we use the static import
statement the code to use the power
function would be much shorter.
double p = pow(a,b);
System.out.println(p);
}} //output: 512.0
Math.sqrt()
The Math.sqrt() function is used when we
want to find the square root of a number
System.out.println(positive);
}
} // Output:20.2
Math.random()
This functions outputs a random number
from a given group of numbers
}
}//Output: Player one roll 3
Math.round()
The Math.round() function results in the
closest value to the integer
System.out.println(num1 + "\n" +
num2);
}
}//Output: 1223.0
Math.ceil()
The Math.ceil() also outputs decimal
numbers as whole numbers
}
} //Output : 11.0
-43.0
Math.floor()
The Math.floor() does the exact opposite
to Math.ceil()
For example;
◦ 13.3 would result in 13
◦ -11.5 would result in -12
import static java.lang.Math.*;
class floor{
public static void main(String args[]){
}
}// 10.0
-46.0