1 import static java.lang.Math.*; // gratuitous test of static import
2 import static java.lang.System.out; // ditto
5 enum Color { red, green, blue ; };
6 public static void main(String... args/* varargs */) {
7 /* for each on multi-dimensional array */
8 int[][] iaa = new int[10][10];
11 out.print(i); // use static import.
14 /** alternate syntax: */
15 for each (int ia[] in iaa)
16 for each (int i in ia) {
20 for (Color c : Color.VALUES) {
22 case Color.red: out.print("R"); break;
23 case Color.green: out.print("G"); break;
24 case Color.blue: out.print("B"); break;
25 default: assert false;
30 // complex enum declaration, from JSR-201
31 public static enum Coin {
32 penny(1), nickel(5), dime(10), quarter(25);
33 Coin(int value) { this.value = value; }
34 private final int value;
35 public int value() { return value; }
37 public static class Card implements Comparable, java.io.Serializable {
38 public enum Rank { deuce, three, four, five, six, seven, eight, nine,
39 ten, jack, queen, king, ace }
40 public enum Suit { clubs, diamonds, hearts, spades }
42 private final Rank rank;
43 private final Suit suit;
45 private Card(Rank rank, Suit suit) {
46 if (rank == null || suit == null)
47 throw new NullPointerException(rank + ", " + suit);
52 public Rank rank() { return rank; }
53 public Suit suit() { return suit; }
55 public String toString() { return rank + " of " + suit; }
57 public int compareTo(Object o) {
59 int rankCompare = rank.compareTo(c.rank);
60 return rankCompare != 0 ? rankCompare : suit.compareTo(c.suit);
63 private static List sortedDeck = new ArrayList(52);
64 /* BROKEN IN PROTOTYPE 2.0 */
66 for (Rank rank : Rank.VALUES)
67 for (Suit suit : Suit.VALUES)
68 sortedDeck.add(new Card(rank, suit));
71 // Returns a shuffled deck
72 public static List newDeck() {
73 List result = new ArrayList(sortedDeck);
74 Collections.shuffle(result);
78 // sophisticated example:
79 public static abstract enum Operation {
81 double eval(double x, double y) { return x + y; }
84 double eval(double x, double y) { return x - y; }
87 double eval(double x, double y) { return x * y; }
90 double eval(double x, double y) { return x / y; }
93 // Perform arithmetic operation represented by this constant
94 abstract double eval(double x, double y);
96 public static void main(String args[]) {
97 double x = Double.parseDouble(args[0]);
98 double y = Double.parseDouble(args[1]);
100 for (Operation op : VALUES)
101 out.println(x + " " + op + " " + y + " = " + op.eval(x, y));