2.9 Using the Math Class
In this section, you are going to take a look at another class in the java.lang
package, the Math
class. The Math
class is a class that only contains static methods that are used for specific purposes.
Several of the methods that are used from the Math
class perform basic math functions. These are listed in the table below.
Method | Use |
---|---|
Math.abs(x) |
Returns the absolute value of x. This can take either an int or a double . |
Math.pow(base, exponent) |
Returns the value of base raised to the power of exponent. |
Math.sqrt(x) |
Returns the positive square root of x. |
As a reminder, since the math class contains only static methods, you do not need to instantiate an object to use it. Static methods are called using the dot operator along with the class name.
Take a look at the Math
class in action in this example.
Another useful method from the Math
class is the random method. The random method takes no input and returns a random number from zero to one, inclusive of zero, but not inclusive of one.
Now you may be thinking that a random number between zero and one is not that useful, however, the number can be manipulated to generate a random number in any range. Using three basic operations, you can convert the output of Math.random()
into any random number you need.
Multiply - By multiplying the results of Math.random()
, you can create values from 0 up to (but not including) the number you multiple by.
Add - Adding to the results offsets the range that you will get from the random number.
Casting to an integer - Finally, if you cast the value to an integer, you will truncate the value and only have random whole numbers.
Watch out! Be careful, a common mistake that programers make is to cast the value at the wrong place. You must include the multiplier inside parentheses along with the random call. If you do not, you will end up casting only the Math.random()
part, and since it is always less than one, your random function will always result in zero. The offset addition operation can either be inside or outside the parentheses.
-
Incorrect
Correct
No Answer was selected
Invalid Answer
What range of numbers would be generated by using:
Here is a Circle
class.
Implement getArea
and getCircumference
by using methods from the Math
class.