Unit 2: Using Objects
Math And Wrapper Classes
Adapted from:
1) Building Java Programs: A Back to Basics Approach
by Stuart Reges and Marty Stepp
2) Runestone CSAwesome Curriculum

2
Static Methods
The Math class has many useful
static
methods. The class is part of the
java.lang package
(group of classes) that is available by default(no need to
import to use). To call these, use the syntax:
Math.
methodName
(
parameters
);
double answer = Math.sqrt(9.2);
int b = Math.round(5.6755);

3
Java's
Math
class
Method name
Description
int abs(int x)
double abs(double x)
returns the absolute value of a int or double
value (overloaded method)
double pow(double base,
double exponent)
Returns the value of the first parameter raised
to the power of the second parameter
double sqrt(double x)
Returns the positive square root of a double
value
double random()
Returns a random double value
greater than
or equal
to 0.0 and
less than
1.0
Constant
Description
Math.E
2.7182818...
Math.PI
3.1415926...

4
Calling
Math
methods
•
Examples:
double squareRoot =
Math.sqrt(121.0)
;
System.out.println(squareRoot);
// 11.0
int absoluteValue =
Math.abs(-50)
;
System.out.println(absoluteValue);
// 50
System.out.println(
Math.min(3, 7)
+ 2);
// 5
•
The
Math
methods do not print to the console.


You've reached the end of your free preview.
Want to read all 21 pages?
- Fall '20
- Subroutine, Marty Stepp, Stuart Reges, double answer