80 likes | 95 Views
CS 115. OBJECT ORIENTED PROGRAMMING I LECTURE 4 part 3 GEORGE KOUTSOGIANNAKIS. Topic. Math Library Class. About the Math Library class. The Math class provides static constants and static methods for performing common calculations.
E N D
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 4 part 3 GEORGE KOUTSOGIANNAKIS
Topic • Math Library Class.
About the Math Library class • The Math class provides static constants and static methods for performing common calculations. • The Math class is in the java.lang package, so it does not need to be imported • The methods of this class are all static. • A static method is a method that can be invoked (called) by using the name of the class that it belongs and the . Operator • For example to call the method random ( a method that produces random numbers) we use Math.random();
Math Library class • Checking the API documentation for random we see the description: public static double random() Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. Returned values are chosen pseudorandomly with (approximately) uniform distribution from that range.
Math Library class Two static constants PI - the value of pi E - the base of the natural logarithm Example: System.out.println( Math.PI ); System.out.println( Math.E ); The output is: 3.141592653589793 2.718281828459045
The Math min/max Methods Find smallest of three numbers: int smaller = Math.min( num1, num2 ); int smallest = Math.min( smaller, num3 ); See Example 3.16 in Text -MathMinMaxMethods.java
Another Example program using the Math Class import java.util.Scanner; public class MyMathClass { public static void main(String[] args) { double exponent=4.0; double result=0.00; double sqrt=0.00; result=Math.pow(10, exponent); sqrt=Math.sqrt(exponent); System.out.println("The result is"+“ "+result); System.out.println("The square root of the number”+” “++exponent+” ”+” is"+” “+sqrt); } }