Java Reference
In-Depth Information
The class Math contains a very useful method, pow , called the method power , which
is used to calculate x y in a program, that is, Math.pow(x, y) = x y . For example,
Math.pow(2,3) = 2 3 = 8 and Math.pow(4, 0.5) = 4 0.5 =
p
4
= 2 . The numbers x
and y used in the method pow are called the (actual) parameters of the method pow . For
example, in Math.pow(2, 3) , the parameters are 2 and 3 .
An expression such as Math.pow(2, 3) is called a method call, and causes the code
attached to the method pow to execute and, in this case, computes 2 3 . The method pow
computes a value of type double . Therefore, we say that the return type of the method
pow is double or the method pow is of type double .
In general, to use a predefined method in a program:
1. You need to know the name of the class containing the method.
2. You need to know the name of the package containing the class and
import this class from the package in the program.
3. You need to know the name of the method as well as the number of
parameters the method takes, the type of each parameter, and the order
of the parameters. You must also be aware of the return type of the
method or, loosely speaking, what the method produces.
For example, to use the method nextInt , you import the class Scanner from the
package java.util .
3
As noted in Chapter 2, the Java system automatically imports methods and class es
from the package java.lang . Therefore, you do not need to import any contents of
the package java.lang explicitly. Because the class Math is contained in the
package java.lang , to use the method pow , you need to know that the name of the
method is pow , that the method pow has two parameters, both of which are numbers, and
that the method calculates the first parameter to the power of the second parameter.
The program in the following example illustrates how to use predefined methods in a
program. More specifically, we use some math methods. Later in this chapter, after
introducing the class String , we will show how to use String methods in a program.
EXAMPLE 3-1
public class PredefinedMethods
{
public static void main(String[] args)
{
double u, v;
System.out.println("Line 1: 2 to the power "
+ "of 6 = " + Math.pow(2, 6));
//Line 1
 
Search WWH ::




Custom Search