Java import static java lang math

Beyond Basic Arithmetic

The Java programming language supports basic arithmetic with its arithmetic operators: +, -, *, /, and %. The Math class in the java.lang package provides methods and constants for doing more advanced mathematical computation.

The methods in the Math class are all static, so you call them directly from the class, like this:

Note: Using the static import language feature, you don’t have to write Math in front of every math function:

import static java.lang.Math.*;

This allows you to invoke the Math class methods by their simple names. For example:

Constants and Basic Methods

The Math class includes two constants:

  • Math.E , which is the base of natural logarithms, and
  • Math.PI , which is the ratio of the circumference of a circle to its diameter.

The Math class also includes more than 40 static methods. The following table lists a number of the basic methods.

Basic Math Methods

Method Description
double abs(double d)
float abs(float f)
int abs(int i)
long abs(long lng)
Returns the absolute value of the argument.
double ceil(double d) Returns the smallest integer that is greater than or equal to the argument. Returned as a double.
double floor(double d) Returns the largest integer that is less than or equal to the argument. Returned as a double.
double rint(double d) Returns the integer that is closest in value to the argument. Returned as a double.
long round(double d)
int round(float f)
Returns the closest long or int, as indicated by the method’s return type, to the argument.
double min(double arg1, double arg2)
float min(float arg1, float arg2)
int min(int arg1, int arg2)
long min(long arg1, long arg2)
Returns the smaller of the two arguments.
double max(double arg1, double arg2)
float max(float arg1, float arg2)
int max(int arg1, int arg2)
long max(long arg1, long arg2)
Returns the larger of the two arguments.
Читайте также:  Head First Lounge Elixirs

The following program, BasicMathDemo , illustrates how to use some of these methods:

public class BasicMathDemo < public static void main(String[] args) < double a = -191.635; double b = 43.74; int c = 16, d = 45; System.out.printf("The absolute value " + "of %.3f is %.3f%n", a, Math.abs(a)); System.out.printf("The ceiling of " + "%.2f is %.0f%n", b, Math.ceil(b)); System.out.printf("The floor of " + "%.2f is %.0f%n", b, Math.floor(b)); System.out.printf("The rint of %.2f " + "is %.0f%n", b, Math.rint(b)); System.out.printf("The max of %d and " + "%d is %d%n", c, d, Math.max(c, d)); System.out.printf("The min of of %d " + "and %d is %d%n", c, d, Math.min(c, d)); >>

Here’s the output from this program:

The absolute value of -191.635 is 191.635 The ceiling of 43.74 is 44 The floor of 43.74 is 43 The rint of 43.74 is 44 The max of 16 and 45 is 45 The min of 16 and 45 is 16

Exponential and Logarithmic Methods

The next table lists exponential and logarithmic methods of the Math class.

Exponential and Logarithmic Methods

Method Description
double exp(double d) Returns the base of the natural logarithms, e, to the power of the argument.
double log(double d) Returns the natural logarithm of the argument.
double pow(double base, double exponent) Returns the value of the first argument raised to the power of the second argument.
double sqrt(double d) Returns the square root of the argument.

The following program, ExponentialDemo , displays the value of e , then calls each of the methods listed in the previous table on arbitrarily chosen numbers:

public class ExponentialDemo < public static void main(String[] args) < double x = 11.635; double y = 2.76; System.out.printf("The value of " + "e is %.4f%n", Math.E); System.out.printf("exp(%.3f) " + "is %.3f%n", x, Math.exp(x)); System.out.printf("log(%.3f) is " + "%.3f%n", x, Math.log(x)); System.out.printf("pow(%.3f, %.3f) " + "is %.3f%n", x, y, Math.pow(x, y)); System.out.printf("sqrt(%.3f) is " + "%.3f%n", x, Math.sqrt(x)); >>

Here’s the output you’ll see when you run ExponentialDemo :

The value of e is 2.7183 exp(11.635) is 112983.831 log(11.635) is 2.454 pow(11.635, 2.760) is 874.008 sqrt(11.635) is 3.411

Trigonometric Methods

The Math class also provides a collection of trigonometric functions, which are summarized in the following table. The value passed into each of these methods is an angle expressed in radians. You can use the toRadians method to convert from degrees to radians.

Trigonometric Methods

Method Description
double sin(double d) Returns the sine of the specified double value.
double cos(double d) Returns the cosine of the specified double value.
double tan(double d) Returns the tangent of the specified double value.
double asin(double d) Returns the arcsine of the specified double value.
double acos(double d) Returns the arccosine of the specified double value.
double atan(double d) Returns the arctangent of the specified double value.
double atan2(double y, double x) Converts rectangular coordinates (x, y) to polar coordinate (r, theta) and returns theta .
double toDegrees(double d)
double toRadians(double d)
Converts the argument to degrees or radians.

Here’s a program, TrigonometricDemo , that uses each of these methods to compute various trigonometric values for a 45-degree angle:

public class TrigonometricDemo < public static void main(String[] args) < double degrees = 45.0; double radians = Math.toRadians(degrees); System.out.format("The value of pi " + "is %.4f%n", Math.PI); System.out.format("The sine of %.1f " + "degrees is %.4f%n", degrees, Math.sin(radians)); System.out.format("The cosine of %.1f " + "degrees is %.4f%n", degrees, Math.cos(radians)); System.out.format("The tangent of %.1f " + "degrees is %.4f%n", degrees, Math.tan(radians)); System.out.format("The arcsine of %.4f " + "is %.4f degrees %n", Math.sin(radians), Math.toDegrees(Math.asin(Math.sin(radians)))); System.out.format("The arccosine of %.4f " + "is %.4f degrees %n", Math.cos(radians), Math.toDegrees(Math.acos(Math.cos(radians)))); System.out.format("The arctangent of %.4f " + "is %.4f degrees %n", Math.tan(radians), Math.toDegrees(Math.atan(Math.tan(radians)))); >>

The output of this program is as follows:

The value of pi is 3.1416 The sine of 45.0 degrees is 0.7071 The cosine of 45.0 degrees is 0.7071 The tangent of 45.0 degrees is 1.0000 The arcsine of 0.7071 is 45.0000 degrees The arccosine of 0.7071 is 45.0000 degrees The arctangent of 1.0000 is 45.0000 degrees

Random Numbers

int number = (int)(Math.random() * 10);

By multiplying the value by 10, the range of possible values becomes 0.0

Using Math.random works well when you need to generate a single random number. If you need to generate a series of random numbers, you should create an instance of java.util.Random and invoke methods on that object to generate numbers.

Источник

Using Package Members

The types that comprise a package are known as the package members.

To use a public package member from outside its package, you must do one of the following:

  • Refer to the member by its fully qualified name
  • Import the package member
  • Import the member’s entire package

Each is appropriate for different situations, as explained in the sections that follow.

Referring to a Package Member by Its Qualified Name

So far, most of the examples in this tutorial have referred to types by their simple names, such as Rectangle and StackOfInts . You can use a package member’s simple name if the code you are writing is in the same package as that member or if that member has been imported.

However, if you are trying to use a member from a different package and that package has not been imported, you must use the member’s fully qualified name, which includes the package name. Here is the fully qualified name for the Rectangle class declared in the graphics package in the previous example.

You could use this qualified name to create an instance of graphics.Rectangle :

graphics.Rectangle myRect = new graphics.Rectangle();

Qualified names are all right for infrequent use. When a name is used repetitively, however, typing the name repeatedly becomes tedious and the code becomes difficult to read. As an alternative, you can import the member or its package and then use its simple name.

Importing a Package Member

To import a specific member into the current file, put an import statement at the beginning of the file before any type definitions but after the package statement, if there is one. Here’s how you would import the Rectangle class from the graphics package created in the previous section.

Now you can refer to the Rectangle class by its simple name.

Rectangle myRectangle = new Rectangle();

This approach works well if you use just a few members from the graphics package. But if you use many types from a package, you should import the entire package.

Importing an Entire Package

To import all the types contained in a particular package, use the import statement with the asterisk (*) wildcard character.

Now you can refer to any class or interface in the graphics package by its simple name.

Circle myCircle = new Circle(); Rectangle myRectangle = new Rectangle();

The asterisk in the import statement can be used only to specify all the classes within a package, as shown here. It cannot be used to match a subset of the classes in a package. For example, the following does not match all the classes in the graphics package that begin with A .

// does not work import graphics.A*;

Instead, it generates a compiler error. With the import statement, you generally import only a single package member or an entire package.

Note: Another, less common form of import allows you to import the public nested classes of an enclosing class. For example, if the graphics.Rectangle class contained useful nested classes, such as Rectangle.DoubleWide and Rectangle.Square , you could import Rectangle and its nested classes by using the following two statements.

import graphics.Rectangle; import graphics.Rectangle.*;

Be aware that the second import statement will not import Rectangle .

Another less common form of import , the static import statement, will be discussed at the end of this section.

For convenience, the Java compiler automatically imports two entire packages for each source file: (1) the java.lang package and (2) the current package (the package for the current file).

Apparent Hierarchies of Packages

At first, packages appear to be hierarchical, but they are not. For example, the Java API includes a java.awt package, a java.awt.color package, a java.awt.font package, and many others that begin with java.awt . However, the java.awt.color package, the java.awt.font package, and other java.awt.xxxx packages are not included in the java.awt package. The prefix java.awt (the Java Abstract Window Toolkit) is used for a number of related packages to make the relationship evident, but not to show inclusion.

Importing java.awt.* imports all of the types in the java.awt package, but it does not import java.awt.color , java.awt.font , or any other java.awt.xxxx packages. If you plan to use the classes and other types in java.awt.color as well as those in java.awt , you must import both packages with all their files:

import java.awt.*; import java.awt.color.*;

Name Ambiguities

If a member in one package shares its name with a member in another package and both packages are imported, you must refer to each member by its qualified name. For example, the graphics package defined a class named Rectangle . The java.awt package also contains a Rectangle class. If both graphics and java.awt have been imported, the following is ambiguous.

In such a situation, you have to use the member’s fully qualified name to indicate exactly which Rectangle class you want. For example,

The Static Import Statement

There are situations where you need frequent access to static final fields (constants) and static methods from one or two classes. Prefixing the name of these classes over and over can result in cluttered code. The static import statement gives you a way to import the constants and static methods that you want to use so that you do not need to prefix the name of their class.

The java.lang.Math class defines the PI constant and many static methods, including methods for calculating sines, cosines, tangents, square roots, maxima, minima, exponents, and many more. For example,

public static final double PI = 3.141592653589793; public static double cos(double a)

Ordinarily, to use these objects from another class, you prefix the class name, as follows.

double r = Math.cos(Math.PI * theta);

You can use the static import statement to import the static members of java.lang.Math so that you don’t need to prefix the class name, Math . The static members of Math can be imported either individually:

import static java.lang.Math.PI;
import static java.lang.Math.*;

Once they have been imported, the static members can be used without qualification. For example, the previous code snippet would become:

Obviously, you can write your own classes that contain constants and static methods that you use frequently, and then use the static import statement. For example,

import static mypackage.MyConstants.*;

Note: Use static import very sparingly. Overusing static import can result in code that is difficult to read and maintain, because readers of the code won’t know which class defines a particular static object. Used properly, static import makes code more readable by removing class name repetition.

Источник

Оцените статью