google search

Custom Search

Friday, August 8, 2008

Beyond Basic Arithmetic(Constants and Basic Methods)

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:

Math.cos(angle);

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:

cos(angle);

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.

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

0 comments:

 

blogger templates | Make Money Online