Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 4 part 3 GEORGE KOUTSOGIANNAKIS.

Similar presentations


Presentation on theme: "CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 4 part 3 GEORGE KOUTSOGIANNAKIS."— Presentation transcript:

1 CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 4 part 3 GEORGE KOUTSOGIANNAKIS

2 Topic Math Library Class.

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

4 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. 4

5 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 5

6 Sample Methods of the Math Class Return typeMethod name and argument list dataTypeOfArgabs( dataType arg ) returns the absolute value of the argument arg, which can be a double, float, int or long. doublelog( double a ) returns the natural logarithm (in base e) of its argument. doublesqrt( double a ) returns the positive square root of a double pow( double base, double exp ) returns the value of base raised to the power exp

7 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 Return typeMethod name and argument list dataTypeOfArgsmin( dataType a, dataType b ) returns the smaller of the two arguments. The arguments can be doubles, floats, ints, or longs. dataTypeOfArgsmax( dataType a, dataType b ) returns the larger of the two arguments. The arguments can be doubles, floats, ints, or longs.

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


Download ppt "CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 4 part 3 GEORGE KOUTSOGIANNAKIS."

Similar presentations


Ads by Google