By David Flanagan
Book Price: $44.95 USD
£31.95 GBP
PDF Price: $35.99
Cover | Table of Contents | Colophon
1 /**
2 * This program computes the factorial of a number
3 */
4 public class Factorial { // Define a class
5 public static void main(String[] args) { // The program starts here
6 int input = Integer.parseInt(args[0]); // Get the user's input
7 double result = factorial(input); // Compute the factorial
8 System.out.println(result); // Print out the result
9 } // The main() method ends here
10
11 public static double factorial(int x) { // This method computes x!
12 if (x < 0) // Check for bad input
13 return 0.0; // If bad, return 0
14 double fact = 1.0; // Begin with an initial value
15 while(x > 1) { // Loop until x equals 1
16 fact = fact * x; // Multiply by x each time
17 x = x - 1; // And then decrement x
18 } // Jump back to start of loop
19 return fact; // Return the result
20 } // factorial() ends here
21 } // The class ends herepackage
declaration followed by zero or
more import
declarations. These declarations
specify the namespace within which the compilation unit will define
names, and the namespaces from which the compilation unit imports
names. We'll see package and
import again in Section 2.10 later in this chapter.package and import
declarations are followed by zero or more
reference type definitions.
These are typically class or
interface definitions, but in Java 5.0 and later,
they can also be enum definitions or annotation
definitions. The general features of reference types are covered
later in this chapter, and detailed coverage of the various kinds of
reference types is in Chapters Chapter 3 and
Chapter 4.\u
xxxx,
in other words, a backslash and a lowercase u, followed by four
hexadecimal characters. For example, \u0020 is the
space character, and \u03c0 is the character .|
Type
|
Contains
|
Default
|
Size
|
Range
|
|---|---|---|---|---|
boolean
|
true or false
|
false
|
1 bit
|
NA
|
char
|
Unicode character
|
\u0000
|
16 bits
|
\u0000 to \uFFFF
|
1.7 // A floating-point literal true // A boolean literal sum // A variable
sum = 1.7
sum = 1 + 2 + 3*1.2 + (4 + 8)/3.0 sum/Math.sqrt(3.0 * 1.234) (int)(sum + 33)
|
Statement
|
Purpose
|
Syntax
|
|---|---|---|
|
expression
|
side effects
|
var
=
expr
;
expr
++;
method
( );
new
Type
(
);
|
|
compound
|
group statements
|
{
statements
}
|
|
empty
|
do nothing
|
;
|
|
labeled
|
modifiers type name ( paramlist ) [ throws exceptions ]
Point to represent a data point in the
two-dimensional Cartesian coordinate system. This class would define
fields (each of type double) to hold the X and Y
coordinates of a point and methods to manipulate and operate on the
point. The Point class is a new data type.char is a data type: it
represents Unicode characters. But a char value
represents a single specific character. A class is a data type; a
class value is called an object. We use the name
class because each class defines a type (or kind, or species, or
class) of objects. The Point class is a data type
that represents X,Y points, while a Point object
represents a single specific X,Y point. As you might imagine, classes
and their objects are closely linked. In the sections that follow, we
will discuss both.Point class we have been
discussing:/** Represents a Cartesian (x,y) point */
public class Point {
public double x, y; // The coordinates of the point
public Point(double x, double y) { // A constructor that
this.x = x; this.y = y; // initializes the fields
}
public double distanceFromOrigin( ) { // A method that operates on
return Math.sqrt(x*x + y*y); // the x and y fields
}
}byte b; // byte is a primitive type byte[] arrayOfBytes; // byte[] is an array type: array of byte byte[][] arrayOfArrayOfBytes; // byte[][] is another type: array of byte[] String[] points; // String[] is an array of String objects
int values, for
example. If a method parameter is of type int[ ],
a caller can pass an array with any number (including zero) of
elements.java.lang.Object. Arrays implement the
Cloneable
interface and
override the Point and use objects of this newly defined type
to store and manipulate X,Y points in a Cartesian coordinate system.
The same program might use an array of characters—of type
char[ ]—to store text and might use an array
of Point objects—of type Point[
]—to store a sequence of points.Point class, for example, might
hold two double values to represent the X and Y
coordinates of the points. The char[ ] and
Point[ ] array types are obviously aggregate types
because they hold a sequence of primitive char
values or Point objects.java. For example, the most fundamental
classes of the language are in the package
java.lang. Various utility classes are in
java.util. Classes for input and output are in
java.io, and classes for networking are in
java.net. Some of these packages contain
subpackages, such as java.lang.reflect and
java.util.regex. Extensions to the
Java platform that have been
standardized by Sun typically have package names that begin with
javax. Some of these extensions, such as
javax.swing and its myriad subpackages, were later
adopted into the core platform itself. Finally, the Java platform
also includes several "endorsed standards,"
which have packages named after the standards body that created them,
such as org.w3c and org.omg.String class, for example, is
part of the java.lang package, so its fully
qualified name is java.lang.String.package declaration.
The packagepackage directiveimport or import
static directivespackage and
import directives, which are not true statements)
must appear within methods, and all methods must appear within a type
definition.public. A
public class is one that is designed for use by
other classes in other packages. This restriction on public classes
only applies to top-level classes; a class can contain any number of
nested or inner classes that are declared public.
We'll see more about the public
modifier and nested classes in Chapter 3.public class, the name of the file
must be the same as the name of the class, with the extension
.java appended. Thus, if
Point is defined as a public
class, its source code must appear in a file named
Point.java. Regardless of whether your classes
are public or not, it is good programming practice
to define only one per file and to give the file the same name as the
class.public static void main(String[] args)
main( )
method is the main entry point for your
program. It is where the Java interpreter starts running. This
method is passed an array of strings and returns no value. When
main( ) returns, the Java interpreter exits
(unless main( ) has created separate threads, in
which case the interpreter waits for all those threads to exit).main( ) method.
Note that you specify the name of the class, not
the name of the class file that contains the class. Any additional
arguments you specify on the command line are passed to the
main( ) method as its String[ ]
parameter. You may also need to specify the
-classpath option (or -cp) to
tell the interpreter where to look for the classes needed by the
program. Consider the following command:% java -classpath /usr/local/Jude com.davidflanagan.jude.Jude datafile.jude
com.davidflanagan.jude.Jude is the name of the
program to run (i.e., the name of the class that defines the
main( ) method). Finally,
datafile.jude is a string that is passed to that
main( ) method as the single element of an array
of String objects.% java -jar /usr/local/Jude/jude.jar datafile.jude
#define,
#include, and #ifdef
directives. Constant definitions are replaced with
static
final fields in Java.
(See the java.lang.Math.PI field for an example.)
Macro definitions are not available in Java, but advanced compiler
technology and inlining has made them less useful. Java does not
require an #include directive because Java has no
header files. Java class files contain both the class API and the
class implementation, and the compiler reads API information from
class files as necessary. Java lacks any form of conditional
compilation, but its cross-platform portability means that this
feature is rarely needed.short,
int, and long types is
platform-dependent, which hampers portability.&, dereference operator like
* or ->, or
sizeof operator. Pointers are a notorious source
of bugs. Eliminating them simplifies the language and makes Java
programs more robust and secure.Point type defined in Chapter 2. An
object
is an instance of a class. The
Point class defines a type that is the set of all
possible two-dimensional points. A Point object is
a value of that type: it represents a single two-dimensional point.new
keyword and a constructor invocation, as shown here:Point p = new Point(1.0, 2.0);
class followed by the name of the class and a set
of class members within curly braces. The class
keyword may be preceded by modifier keywords and annotations (see
Chapter 4). If the class extends another class,
the class name is followed by the extends keyword
and the name of the class being extended.
If the class
implements one or more interfaces then the class name or the
extends clause is followed by the
implements
keyword and a comma-separated list of interface names. For example:public class Integer extends Number implements Serializable, Comparable {
// class members go here
}public
public
class is visible to classes
defined outside of its package. See Section 3.6 later in this chapter.abstract
abstract class is one whose implementation is
incomplete and cannot be instantiated. Any class with one or more
abstract methods must be declared
abstract.final
final
modifier
specifies that the class may not be extended. Declaring a class
final may enable the Java VM to optimize its
methods.strictfp
strictfp
, all its methods behave as if they
were declared strictfp. This rarely used modifier
is discussed in Section 2.6 in
Chapter 2.abstract and
final. By convention, if a class has more than one
modifier, they appear in the order shown.Circle, shown in Example 3-1, contains all four types of members.public class Circle {
// A class field
public static final double PI= 3.14159; // A useful constant
// A class method: just compute a value based on the arguments
public static double radiansToDegrees(double rads) {
return rads * 180 / PI;
}
// An instance field
public double r; // The radius of the circle
// Two instance methods: they operate on the instance fields of an object
public double area() { // Compute the area of the circle
return PI * r * r;
}
public double circumference() { // Compute the circumference of the circle
return 2 * PI * r;
}
}Circle objects:Circle c = new Circle();
Circle class in Example 3-1,
Java gave us a default constructor that takes no arguments and
performs no special initialization.new operator creates a new, but
uninitialized, instance of the class. The constructor method is then
called, with the new object passed implicitly (a
this reference, as we saw earlier) as well as
whatever arguments that are specified between parentheses passed
explicitly. The constructor can use these arguments to do whatever
initialization is necessary.Circle that contains a constructor that lets us
specify the radius of a new Circle object. The
constructor also uses the this reference to
distinguish between a method parameter and an instance field of the
same name.public class Circle {
public static final double PI = 3.14159; // A constant
public double r; // An instance field that holds the radius of the circle
// The constructor method: initialize the radius field
public Circle(double r) { this.r = r; }
// The instance methods: compute values based on the radius
public double circumference() { return 2 * PI * r; }
public double area() { return PI * r*r; }
}free()
function or the delete operator to reclaim memory.
The fact that you don't need to remember to destroy
every object you create is one of the features that makes Java a
pleasant language to work with. It is also one of the features that
makes programs written in Java less prone to bugs than those written
in languages that don't support automatic garbage
collection.