Java Reference
In-Depth Information
➤
java.lang.System
: Class providing system operations.
➤
java.lang.Math
: Class providing methods to perform basic mathematics.
Other than this, this package also provides a number of classes to deal with complex Java aspects
such as reference management, reflection, and process spawning and control. All advanced concepts
which you can safely ignore for now.
The two classes that jump out, however, and that can be very useful are the
Math
and
StringBuilder
classes.
Math contains two static constants (
E
, the base of natural logarithms, and
PI
, the ratio of the cir-
cumference of a circle to its diameter), as well as a number of methods—
abs
,
max
,
min
,
ceil
,
floor
,
sin
,
cos
,
tan
,
pow
, and
sqrt
—to help out with mathematics when programming.
Mathematics in Java
try it out
Here is a short exercise to begin using mathematics in Java.
1.
Create a
MathTester
class in Eclipse with the following content:
class MathTester {
public static void main(String[] args) {
double num1 = 2.34;
double num2 = 1.56;
System.out.println(Math.max(num1, num2));
System.out.println(Math.min(num1, num2));
System.out.println(Math.sqrt(num1));
System.out.println(Math.pow(num1, num2));
}
}
2.
Run the
main
method and observe the output.
How It Works
Now take a look at how it works.
1.
The
Math
class contains a number of methods to help out with mathematics when programming.
Take your time to explore other methods using Eclipse's context menu.
2.
Since the
Math
class belongs to the
java.lang
package, you do not need to write an
import
state-
ment but can use this class directly.
3.
All of
Math
's methods are
static
, meaning that you do not have to create a
Math
object to be able
to use its methods. This is a common pattern for “utility” classes in Java, which are classes con-
taining a set of helpful grouped methods that can be statically accessed.
The
StringBuilder
class represents a mutable sequence of characters, compared to a normal String that
represents an immutable sequence of characters (which is why Java creates a new
String
object every
time you modify a String). The following Try It Out shows where the
StringBuilder
can be useful.
Search WWH ::
Custom Search