Commit d03de727 authored by O'Reilly Media, Inc.'s avatar O'Reilly Media, Inc.

Initial commit

parents
9780596007737
\ No newline at end of file
/**
* This program computes the factorial of a number
*/
public class Factorial { // Define a class
public static void main(String[] args) { // The program starts here
int input = Integer.parseInt(args[0]); // Get the user's input
double result = factorial(input); // Compute the factorial
System.out.println(result); // Print out the result
} // The main() method ends here
public static double factorial(int x) { // This method computes x!
if (x < 0) // Check for bad input
return 0.0; // If bad, return 0
double fact = 1.0; // Begin with an initial value
while(x > 1) { // Loop until x equals 1
fact = fact * x; // Multiply by x each time
x = x - 1; // And then decrement x
} // Jump back to start of loop
return fact; // Return the result
} // factorial() ends here
} // The class ends here
import java.util.*;
public class ForInDemo {
public static void main(String[] args) {
// This is a collection we'll iterate over below.
Set<String> wordset = new HashSet<String>();
// We start with a basic loop over the elements of an array.
// The body of the loop is executed once for each element of args[].
// Each time through one element is assigned to the variable word.
for(String word : args) {
System.out.print(word + " ");
wordset.add(word);
}
System.out.println();
// Now iterate through the elements of the Set.
for(String word : wordset) System.out.print(word + " ");
}
}
/** 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
}
}
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;
}
}
public Iterator<Linkable> iterator() {
// The anonymous class is defined as part of the return statement
return new Iterator<Linkable>() {
Linkable current;
// Replace constructor with an instance initializer
{ current = head; }
// The following 3 methods are defined by the Iterator interface
public boolean hasNext() { return current != null; }
public Linkable next() {
if (current == null) throw new java.util.NoSuchElementException();
Linkable value = current;
current = current.getNext();
return value;
}
public void remove() { throw new UnsupportedOperationException(); }
}; // Note the required semicolon. It terminates the return statement
}
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; }
}
public class PlaneCircle extends Circle {
// We automatically inherit the fields and methods of Circle,
// so we only have to put the new stuff here.
// New instance fields that store the center point of the circle
public double cx, cy;
// A new constructor method to initialize the new fields
// It uses a special syntax to invoke the Circle() constructor
public PlaneCircle(double r, double x, double y) {
super(r); // Invoke the constructor of the superclass, Circle()
this.cx = x; // Initialize the instance field cx
this.cy = y; // Initialize the instance field cy
}
// The area() and circumference() methods are inherited from Circle
// A new instance method that checks whether a point is inside the circle
// Note that it uses the inherited instance field r
public boolean isInside(double x, double y) {
double dx = x - cx, dy = y - cy; // Distance from center
double distance = Math.sqrt(dx*dx + dy*dy); // Pythagorean theorem
return (distance < r); // Returns true or false
}
}
package shapes; // Specify a package for the class
public class Circle { // The class is still public
// This is a generally useful constant, so we keep it public
public static final double PI = 3.14159;
protected double r; // Radius is hidden but visible to subclasses
// A method to enforce the restriction on the radius
// This is an implementation detail that may be of interest to subclasses
protected void checkRadius(double radius) {
if (radius < 0.0)
throw new IllegalArgumentException("radius may not be negative.");
}
// The constructor method
public Circle(double r) {
checkRadius(r);
this.r = r;
}
// Public data accessor methods
public double getRadius() { return r; }
public void setRadius(double r) {
checkRadius(r);
this.r = r;
}
// Methods to operate on the instance field
public double area() { return PI * r * r; }
public double circumference() { return 2 * PI * r; }
}
public abstract class Shape {
public abstract double area(); // Abstract methods: note
public abstract double circumference(); // semicolon instead of body.
}
class Circle extends Shape {
public static final double PI = 3.14159265358979323846;
protected double r; // Instance data
public Circle(double r) { this.r = r; } // Constructor
public double getRadius() { return r; } // Accessor
public double area() { return PI*r*r; } // Implementations of
public double circumference() { return 2*PI*r; } // abstract methods.
}
class Rectangle extends Shape {
protected double w, h; // Instance data
public Rectangle(double w, double h) { // Constructor
this.w = w; this.h = h;
}
public double getWidth() { return w; } // Accessor method
public double getHeight() { return h; } // Another accessor
public double area() { return w*h; } // Implementations of
public double circumference() { return 2*(w + h); } // abstract methods.
}
// This class represents a circle with immutable position and radius.
public class Circle implements Comparable<Circle> {
// These fields hold the coordinates of the center and the radius.
// They are private for data encapsulation and final for immutability
private final int x, y, r;
// The basic constructor: initialize the fields to specified values
public Circle(int x, int y, int r) {
if (r < 0) throw new IllegalArgumentException("negative radius");
this.x = x; this.y = y; this.r = r;
}
// This is a "copy constructor"--a useful alternative to clone()
public Circle(Circle original) {
x = original.x; // Just copy the fields from the original
y = original.y;
r = original.r;
}
// Public accessor methods for the private fields.
// These are part of data encapsulation.
public int getX() { return x; }
public int getY() { return y; }
public int getR() { return r; }
// Return a string representation
@Override public String toString() {
return String.format("center=(%d,%d); radius=%d", x, y, r);
}
// Test for equality with another object
@Override public boolean equals(Object o) {
if (o == this) return true; // Identical references?
if (!(o instanceof Circle)) return false; // Correct type and non-null?
Circle that = (Circle) o; // Cast to our type
if (this.x == that.x && this.y == that.y && this.r == that.r)
return true; // If all fields match
else
return false; // If fields differ
}
// A hash code allows an object to be used in a hash table.
// Equal objects must have equal hash codes. Unequal objects are allowed
// to have equal hash codes as well, but we try to avoid that.
// We must override this method since we also override equals().
@Override public int hashCode() {
int result = 17; // This hash code algorithm from the book
result = 37*result + x; // _Effective Java_, by Joshua Bloch
result = 37*result + y;
result = 37*result + r;
return result;
}
// This method is defined by the Comparable interface.
// Compare this Circle to that Circle. Return a value < 0 if this < that.
// Return 0 if this == that. Return a value > 0 if this > that.
// Circles are ordered top to bottom, left to right, and then by radius
public int compareTo(Circle that) {
long result = that.y - this.y; // Smaller circles have bigger y values
if (result == 0) result = this.x - that.x; // If same compare l-to-r
if (result == 0) result = this.r - that.r; // If same compare radius
// We have to use a long value for subtraction because the differences
// between a large positive and large negative value could overflow
// an int. But we can't return the long, so return its sign as an int.
return Long.signum(result); // new in Java 5.0
}
}
// A class that implements a stack as a linked list
public class LinkedStack {
// This static member interface defines how objects are linked
// The static keyword is optional: all nested interfaces are static
public static interface Linkable {
public Linkable getNext();
public void setNext(Linkable node);
}
// The head of the list is a Linkable object
Linkable head;
// Method bodies omitted
public void push(Linkable node) { ... }
public Object pop() { ... }
}
// This class implements the static member interface
class LinkableInteger implements LinkedStack.Linkable {
// Here's the node's data and constructor
int i;
public LinkableInteger(int i) { this.i = i; }
// Here are the data and methods required to implement the interface
LinkedStack.Linkable next;
public LinkedStack.Linkable getNext() { return next; }
public void setNext(LinkedStack.Linkable node) { next = node; }
}
import java.util.Iterator;
public class LinkedStack {
// Our static member interface
public interface Linkable {
public Linkable getNext();
public void setNext(Linkable node);
}
// The head of the list
private Linkable head;
// Method bodies omitted here
public void push(Linkable node) { ... }
public Linkable pop() { ... }
// This method returns an Iterator object for this LinkedStack
public Iterator<Linkable> iterator() { return new LinkedIterator(); }
// Here is the implementation of the Iterator interface,
// defined as a nonstatic member class.
protected class LinkedIterator implements Iterator<Linkable> {
Linkable current;
// The constructor uses the private head field of the containing class
public LinkedIterator() { current = head; }
// The following 3 methods are defined by the Iterator interface
public boolean hasNext() { return current != null; }
public Linkable next() {
if (current == null) throw new java.util.NoSuchElementException();
Linkable value = current;
current = current.getNext();
return value;
}
public void remove() { throw new UnsupportedOperationException(); }
}
}
// This method returns an Iterator object for this LinkedStack
public Iterator<Linkable> Iterator() {
// Here's the definition of LinkedIterator as a local class
class LinkedIterator implements Iterator<Linkable> {
Linkable current;
// The constructor uses the private head field of the containing class
public LinkedIterator() { current = head; }
// The following 3 methods are defined by the Iterator interface
public boolean hasNext() { return current != null; }
public Linkable next() {
if (current == null) throw new java.util.NoSuchElementException();
Linkable value = current;
current = current.getNext();
return value;
}
public void remove() { throw new UnsupportedOperationException(); }
}
// Create and return an instance of the class we just defined
return new LinkedIterator();
}
// Here is a partial implementation of that interface. Many
// implementations may find this a useful starting point.
public abstract class AbstractRectangularShape implements RectangularShape {
// The position and size of the shape
protected double x, y, w, h;
// Default implementations of some of the interface methods
public void setSize(double width, double height) { w = width; h = height; }
public void setPosition(double x, double y) { this.x = x; this.y = y; }
public void translate (double dx, double dy) { x += dx; y += dy; }
}
public interface Centered {
void setCenter(double x, double y);
double getCenterX();
double getCenterY();
}
public class CenteredRectangle extends Rectangle implements Centered {
// New instance fields
private double cx, cy;
// A constructor
public CenteredRectangle(double cx, double cy, double w, double h) {
super(w, h);
this.cx = cx;
this.cy = cy;
}
// We inherit all the methods of Rectangle but must
// provide implementations of all the Centered methods.
public void setCenter(double x, double y) { cx = x; cy = y; }
public double getCenterX() { return cx; }
public double getCenterY() { return cy; }
}
public class Circle extends Shape {
public static final double PI = 3.14159265358979323846;
protected double r; // Instance data
public Circle(double r) { this.r = r; } // Constructor
public double getRadius() { return r; } // Accessor
public double area() { return PI*r*r; } // Implementations of
public double circumference() { return 2*PI*r; } // abstract methods.
}
class A { // Define a class named A
int i = 1; // An instance field
int f() { return i; } // An instance method
static char g() { return 'A'; } // A class method
}
class B extends A { // Define a subclass of A
int i = 2; // Hides field i in class A
int f() { return -i; } // Overrides instance method f in class A
static char g() { return 'B'; } // Hides class method g() in class A
}
public class OverrideTest {
public static void main(String args[]) {
B b = new B(); // Creates a new object of type B
System.out.println(b.i); // Refers to B.i; prints 2
System.out.println(b.f()); // Refers to B.f(); prints -2
System.out.println(b.g()); // Refers to B.g(); prints B
System.out.println(B.g()); // This is a better way to invoke B.g()
A a = (A) b; // Casts b to an instance of class A
System.out.println(a.i); // Now refers to A.i; prints 1
System.out.println(a.f()); // Still refers to B.f(); prints -2
System.out.println(a.g()); // Refers to A.g(); prints A
System.out.println(A.g()); // This is a better way to invoke A.g()
}
}
public class PlaneCircle extends Circle {
// We automatically inherit the fields and methods of Circle,
// so we only have to put the new stuff here.
// New instance fields that store the center point of the circle
public double cx, cy;
// A new constructor method to initialize the new fields
// It uses a special syntax to invoke the Circle() constructor
public PlaneCircle(double r, double x, double y) {
super(r); // Invoke the constructor of the superclass, Circle()
this.cx = x; // Initialize the instance field cx
this.cy = y; // Initialize the instance field cy
}
// The area() and circumference() methods are inherited from Circle
// A new instance method that checks whether a point is inside the circle
// Note that it uses the inherited instance field r
public boolean isInside(double x, double y) {
double dx = x - cx, dy = y - cy; // Distance from center
double distance = Math.sqrt(dx*dx + dy*dy); // Pythagorean theorem
return (distance < r); // Returns true or false
}
}
public interface Positionable extends Centered {
void setUpperRightCorner(double x, double y);
double getUpperRightX();
double getUpperRightY();
}
public class Rectangle extends Shape {
protected double w, h; // Instance data
public Rectangle(double w, double h) { // Constructor
this.w = w; this.h = h;
}
public double getWidth() { return w; } // Accessor method
public double getHeight() { return h; } // Another accessor
public double area() { return w*h; } // Implementations of
public double circumference() { return 2*(w + h); } // abstract methods.
}
// Here is a basic interface. It represents a shape that fits inside
// of a rectangular bounding box. Any class that wants to serve as a
// RectangularShape can implement these methods from scratch.
public interface RectangularShape {
void setSize(double width, double height);
void setPosition(double x, double y);
void translate(double dx, double dy);
double area();
boolean isInside();
}
public abstract class Shape {
public abstract double area(); // Abstract methods: note
public abstract double circumference(); // semicolon instead of body.
}
public class Weird {
// A static member interface used below
public static interface IntHolder { public int getValue(); }
public static void main(String[] args) {
IntHolder[] holders = new IntHolder[10]; // An array to hold 10 objects
for(int i = 0; i < 10; i++) { // Loop to fill the array up
final int fi = i; // A final local variable
class MyIntHolder implements IntHolder { // A local class
public int getValue() { return fi; } // It uses the final variable
}
holders[i] = new MyIntHolder(); // Instantiate the local class
}
// The local class is now out of scope, so we can't use it. But
// we have 10 valid instances of that class in our array. The local
// variable fi is not in our scope here, but it is still in scope for
// the getValue() method of each of those 10 objects. So call getValue()
// for each object and print it out. This prints the digits 0 to 9.
for(int i = 0; i < 10; i++) System.out.println(holders[i].getValue());
}
}
public enum ArithmeticOperator {
// The enumerated values
ADD, SUBTRACT, MULTIPLY, DIVIDE;
// Value-specific behavior using a switch statement
public double compute(double x, double y) {
switch(this) {
case ADD: return x + y;
case SUBTRACT: return x - y;
case MULTIPLY: return x * y;
case DIVIDE: return x / y;
default: throw new AssertionError(this);
}
}
// Test case for using this enum
public static void main(String args[]) {
double x = Double.parseDouble(args[0]);
double y = Double.parseDouble(args[1]);
for(ArithmeticOperator op : ArithmeticOperator.values())
System.out.printf("%f %s %f = %f%n", x, op, y, op.compute(x,y));
}
}
/**
* Specifies the author of a program element.
*/
public @interface Author {
/** Return the name of the author */
String value();
}
public enum DownloadStatus { CONNECTING, READING, DONE, ERROR }
public interface Espresso {
enum Drink { LATTE, MOCHA, AMERICANO, CAPPUCCINO, ESPRESSO }
enum Size { SHORT, TALL, GRANDE }
enum Strength { SINGLE, DOUBLE, TRIPLE, QUAD }
enum Milk { SKINNY, ONE_PERCENT, TWO_PERCENT, WHOLE, SOY }
enum Caffeine { REGULAR, SPLIT_SHOT, DECAF }
enum Flags { WITH_ROOM, EXTRA_HOT, DRY }
Drink getDrink();
Size getSize();
Strength getStrength();
Milk getMilk();
Caffeine getCaffeine();
java.util.Set<Flags> getFlags();
}
public enum Prefix {
// These are the values of this enumerated type.
// Each one is followed by constructor arguments in parentheses.
// The values are separated from each other by commas, and the
// list of values is terminated with a semicolon to separate it from
// the class body that follows.
MILLI("m", .001),
CENTI("c", .01),
DECI("d", .1),
DECA("D", 10.0),
HECTA("h", 100.0),
KILO("k", 1000.0); // Note semicolon
// This is the constructor invoked for each value above.
Prefix(String abbrev, double multiplier) {
this.abbrev = abbrev;
this.multiplier = multiplier;
}
// These are the private fields set by the constructor
private String abbrev;
private double multiplier;
// These are accessor methods for the fields. They are instance methods
// of each value of the enumerated type.
public String abbrev() { return abbrev; }
public double multiplier() { return multiplier; }
}
import java.lang.annotation.*;
/**
* An annotation of this type represents a single code review of the
* annotated element. Every review must specify the name of the reviewer
* and the grade assigned to the code. Optionally, reviews may also include
* a comment string.
*/
public @interface Review {
// Nested enumerated type
public static enum Grade { EXCELLENT, SATISFACTORY, UNSATISFACTORY };
// These methods define the annotation members
Grade grade(); // member named "grade" with type Grade
String reviewer();
String comment() default ""; // Note default value here.
}
import java.lang.annotation.*;
/**
* An annotation of this type specifies the results of one or more
* code reviews for the annotated element
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface Reviews {
Review[] value();
}
public enum Seasons { WINTER, SPRING, SUMMER, AUTUMN }
import java.util.*;
/**
* A tree is a data structure that holds values of type V.
* Each tree has a single value of type V and can have any number of
* branches, each of which is itself a Tree.
*/
public class Tree<V> {
// The value of the tree is of type V.
V value;
// A Tree<V> can have branches, each of which is also a Tree<V>
List<Tree<V>> branches = new ArrayList<Tree<V>>();
// Here's the constructor. Note the use of the type variable V.
public Tree(V value) { this.value = value; }
// These are instance methods for manipulating the node value and branches.
// Note the use of the type variable V in the arguments or return types.
V getValue() { return value; }
void setValue(V value) { this.value = value; }
int getNumBranches() { return branches.size(); }
Tree<V> getBranch(int n) { return branches.get(n); }
void addBranch(Tree<V> branch) { branches.add(branch); }
}
import java.io.Serializable;
import java.util.*;
public class Tree<V extends Serializable & Comparable<V>>
implements Serializable, Comparable<Tree<V>>
{
V value;
List<Tree<V>> branches = new ArrayList<Tree<V>>();
public Tree(V value) { this.value = value; }
// Instance methods
V getValue() { return value; }
void setValue(V value) { this.value = value; }
int getNumBranches() { return branches.size(); }
Tree<V> getBranch(int n) { return branches.get(n); }
void addBranch(Tree<V> branch) { branches.add(branch); }
// This method is a nonrecursive implementation of Comparable<Tree<V>>
// It only compares the value of this node and ignores branches.
public int compareTo(Tree<V> that) {
if (this.value == null && that.value == null) return 0;
if (this.value == null) return -1;
if (that.value == null) return 1;
return this.value.compareTo(that.value);
}
// javac -Xlint warns us if we omit this field in a Serializable class
private static final long serialVersionUID = 833546143621133467L;
}
import java.util.*;
public class Tree<V> {
// These fields hold the value and the branches
V value;
List<Tree<? extends V>> branches = new ArrayList<Tree<? extends V>>();
// Here's a constructor
public Tree(V value) { this.value = value; }
// These are instance methods for manipulating value and branches
V getValue() { return value; }
void setValue(V value) { this.value = value; }
int getNumBranches() { return branches.size(); }
Tree<? extends V> getBranch(int n) { return branches.get(n); }
void addBranch(Tree<? extends V> branch) { branches.add(branch); }
}
public @interface UncheckedExceptions {
Class<? extends RuntimeException>[] value();
}
import java.lang.annotation.*;
/**
* Specifies that the annotated element is unstable and its API is