side1 = 3.0;
side2 = 4.0;
// Notice how sqrt() and pow() must be qualified by
// their class name, which is Math.
hypot = Math.sqrt(Math.pow(side1, 2) +
Math.pow(side2, 2));
System.out.println("Given sides of lengths " +
side1 + " and " + side2 +
" the hypotenuse is " +
hypot);
}
}
Because pow( ) and sqrt( ) are static methods, they must be called through the use of
their class' name, Math. This results in a somewhat unwieldy hypotenuse calculation:
hypot = Math.sqrt(Math.pow(side1, 2) +
Math.pow(side2, 2));
As this simple example illustrates, having to specify the class name each time pow( ) or
sqrt( ) (or any of Java's other math methods, such as sin( ), cos( ), and tan( )) is used can
grow tedious.
You can eliminate the tedium of specifying the class name through the use of static
import, as shown in the following version of the preceding program:
// Use static import to bring sqrt() and pow() into view.
import static java.lang.Math.sqrt;
import static java.lang.Math.pow;
// Compute the hypotenuse of a right triangle.
class Hypot {
public static void main(String args[]) {
double side1, side2;
double hypot;
side1 = 3.0;
side2 = 4.0;
// Here, sqrt() and pow() can be called by themselves,
// without their class name.
hypot = sqrt(pow(side1, 2) + pow(side2, 2));
System.out.println("Given sides of lengths " +
side1 + " and " + side2 +
" the hypotenuse is " +
hypot);
}
}
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home