The Math class is a class that already exists in Java, and it is a part of the java.lang package. You can use the Math class to perform mathematical operations such as absolute value, exponentiation, and square roots.
The Math class consists of methods that allow to perform these operations. A method is a chunk of code that performs a task. Some methods require data in order to perform that task. Some methods also give a result after performing a tasks: this is called "returning a value".
For example, a Math method called pow() will calculate a number to the power of another number. The pow() method requires some information before it can give you any results. It needs to know the base number and the exponent. You can give the pow() method these two pieces of information and it will return the result of the base number to the power of the exponent. For example, if you wanted to know the result of 72, then you would give the pow() method 7 and 2. The pow() method would then return the value 49.
Math methods are static methods. This means that to invoke them or use them, you need to put the name of the class in front of the method name with a dot or period. For example, to use the pow() method, you refer to it as Math.pow().
If a method needs inputs in order to perform its task, you would put them in the brackets, separated by commas. For example, Math.pow(7, 2) invokes the pow() method using the value 7 as the base number and 2 as the exponent. These inputs are often called arguments or parameters. The pow() method always knows that the first argument you give it is the base number and the second argument is the exponent! When learning about a new method, you need to check its documentation to see if it requires inputs, and if so, what order those inputs should go in.
If a method returns a value or gives you a result, you need to store that result somewhere. The pow() method returns a double value that is the result of the first argument to the power of the second argument. You will need to store this result in a variable most of the time:
double power = Math.pow(7, 2);
You can also output the result instead:
System.out.println(Math.pow(7, 2));
Both of these are correct, but if you need to "remember" the result for use later, you'll need to use a variable as in the first example.
What does the following main method do?
public static void main(String[] args) { Math.pow(7, 2); }
If you're not sure, try it out!
Remember: if a method returns a value, you need to store it somewhere or directly send it to an output device!
1. Use Chapter 4.2 of your textbook or the Math class documentation as a reference. What Math class methods would you use to perform the following tasks:
2. Write a single statement to perform each of the following calculations and store each result in a variable of the appropriate type:
3. Write each of the following expressions as a single Java statement: