Although most methods execute in response to method calls on specific objects, this is not always the case. Sometimes a method performs a task that does not depend on the contents of any object. Such a method applies to the class in which it’s declared as a whole and is known as a static
method or a class method. It’s common for classes to contain convenient static
methods to perform common tasks. For example, recall that we used static
method pow
of class Math
to raise a value to a power in Fig. C.15. To declare a method as static
, place the keyword static
before the return type in the method’s declaration. For any class imported into your program, you can call the class’s static
methods by specifying the name of the class in which the method is declared, followed by a dot (.
) and the method name, as in
ClassName.
methodName(
arguments )
We use various Math
class methods here to present the concept of static
methods. Class Math
provides a collection of methods that enable you to perform common mathematical calculations. For example, you can calculate the square root of 900.0
with the static
method call
Math.sqrt( 900.0 )
The preceding expression evaluates to 30.0
. Method sqrt
takes an argument of type double
and returns a result of type double
. To output the value of the preceding method call in the command window, you might write the statement
System.out.println( Math.sqrt( 900.0 ) );
In this statement, the value that sqrt
returns becomes the argument to method println
. There was no need to create a Math
object before calling method sqrt
. Also all Math
class methods are static
—therefore, each is called by preceding its name with the class name Math
and the dot (.
)separator.
Method arguments may be constants, variables or expressions. Figure D.1 summarizes several Math
class methods. In the figure, x and y are of type double
.