Popular Posts

Wednesday, September 21, 2011

Java Puzzles: advanced puzzlers


public class PoisonParen {

    /*
     * Add a declaration that initializes a field to some expression and
     * compile the program. It must compile without error. Now add a pair
     * of parentheses around a subexpression that serves merely to reinforce
     * the order of evaluation that was performed before you inserted the
     * parentheses.  Recompile the program. If it no longer compiles, then
     * you've solved the puzzle!
     */
}

public class Reflexive {
    public static void main(String[] args) throws Exception {
        /*
         * If you can come up with a primitive type and value
         * that causes this program to print "false", then
         * you have proven that the == operator is not reflexive.
         */
        <typeX> x = <valueX>;

        System.out.println(x == x);
    }
}


public class Symmetric {
    public static void main(String[] args) throws Exception {
        /*
         * If you can come up with a set of primitive types and values
         * that causes this program to print "true false", then
         * you have proven that the == operator is not symmetric.
         */
        <typeX> x = <valueX>;
        <typeY> y = <valueY>;

        System.out.print ((x == y) + " ");
        System.out.println(y == x);
    }
} 

public class Transitive {

    public static void main(String[] args) throws Exception {
        /*
         * If you can come up with a set of primitive types and values
         * that causes this program to print "true true false", then
         * you have proven that the == operator is not transitive.
         */

        <typeX> x = <valueX>;
        <typeY> y = <valueY>;
        <typeZ> z = <valueZ>;

        System.out.print ((x == y) + " ");
        System.out.print ((y == z) + " ");
        System.out.println(x == z);
    }
}


import java.util.*;

public class Pair<T> {
    private final T first;
    private final T second;

    public Pair(T first, T second) {
        this.first = first;
        this.second = second;
    }

    public T first() {
        return first;
    }
    public T second() {
        return second;
    }

    public List<String> stringList() {
        return Arrays.asList(String.valueOf(first),
                             String.valueOf(second));
    }


    public static void main(String[] args) {
        Pair p = new Pair<Object>(23, "skidoo");
        System.out.println(p.first() + " " + p.second());
        for (String s : p.stringList())
            System.out.print(s + " ");
    }
}


public class LinkedList<E> {
    private Node<E> head = null;
    private class Node<E> {

        E value;
        Node<E> next;

        // Node constructor links the node as a new head
        Node(E value) {
            this.value = value;
            this.next = head;
            head = this;
        }
    }


    public void add(E e) {
       new Node<E>(e);
        // Link node as new head
    }


    public void dump() {
        for (Node<E> n = head; n != null; n = n.next)
            System.out.println(n.value + " ");
    }

    public static void main(String[] args) {
        LinkedList<String> list = new LinkedList<String>();
        list.add("world");
        list.add("Hello");
        list.dump();
    }
}


public class Outer {
    class Inner1 extends Outer {}
    class Inner2 extends Inner1 {}
}


import java.util.*;
import java.io.*;

public class SerialKiller {
    public static void main(String[] args) {
        Sub sub = new Sub(666); 
        sub.checkInvariant();

        Sub copy = (Sub) deepCopy(sub);
        copy.checkInvariant();
    }

    // Copies its argument via serialization (See Puzzle 80)
    static public Object deepCopy(Object obj) {
        try {
           ByteArrayOutputStream bos = 
                new ByteArrayOutputStream();
            new ObjectOutputStream(bos).writeObject(obj);
            ByteArrayInputStream bin =
                new ByteArrayInputStream(bos.toByteArray());
            return new ObjectInputStream(bin).readObject(); 
        } catch(Exception e) {
            throw new IllegalArgumentException(e); 
        }
    }
}

class Super implements Serializable {
    final Set<Super> set = new HashSet<Super>();
} 

final class Sub extends Super {
    private int id;
    public Sub(int id) {
        this.id = id;
        set.add(this); // Establish invariant
    }

    public void checkInvariant() {
        if (!set.contains(this))
           throw new AssertionError("invariant violated");
    }

    public int hashCode() {
        return id;
    }

    public boolean equals(Object o) {
        return (o instanceof Sub) && (id == ((Sub)o).id);
    }
}


public class Twisted {
    private final String name;
    Twisted(String name) {
        this.name = name;
    }
    private String name() {
        return name;
    }
    private void reproduce() {
        new Twisted("reproduce") {
            void printName() {
                System.out.println(name());
            }
        }.printName();
    }
    public static void main(String[] args) {
        new Twisted("main").reproduce();
    }
}


public class PrintWords {
    public static void main(String[] args) {
        System.out.println(Words.FIRST  + " " + 
                           Words.SECOND + " " +
                           Words.THIRD);
    }
}
public class Words {
    private Words() { };  // Uninstantiable

    public static final String FIRST  = "the";
    public static final String SECOND = null;
    public static final String THIRD  = "set";
} 

// The second version of the Words class appears below (commented out)
//
// public class Words {
//     private Words() { };  // Uninstantiable
//
//     public static final String FIRST  = "physics";
//     public static final String SECOND = "chemistry";
//     public static final String THIRD  = "biology";
// }


import java.util.Random; 

public class Shuffle {
    private static Random rnd = new Random();
    public static void shuffle(Object[] a) {
        for (int i = 0; i < a.length; i++)
            swap(a, i, rnd.nextInt(a.length));
    }

    private static void swap(Object[] a, int i, int j) {
       Object tmp = a[i];
        a[i] = a[j];
        a[j] = tmp;
    }
}


public class ApplePie {
    public static void main(String[] args) {
        int count = 0;
        for (int i = 0; i < 100; i++); {
            count++;
        }
        System.out.println(count);
    }
}

import java.util.*;

public class BananaBread {
    public static void main(String[] args) {
        Integer[] array = { 3, 1, 4, 1, 5, 9 };
        Arrays.sort(array, new Comparator<Integer>() {
            public int compare(Integer i1, Integer i2) {
                return i1 < i2 ? -1 : (i2 > i1 ? 1 : 0);
            }
        });
        System.out.println(Arrays.toString(array));
    }
}

public class ChocolateCake {
    public static void main(String[] args) {
        System.out.println(true?false:true == true?false:true);
    }
}

Java Puzzles: library puzzlers


public class PingPong {
    public static synchronized void main(String[] a) {
        Thread t = new Thread() {
            public void run() { pong(); }
        };
        t.run();
        System.out.print("Ping");
    }

    static synchronized void pong() {
        System.out.print("Pong");
    }
}


import java.util.*;

public class Worker extends Thread {
    private volatile boolean quittingTime = false;
    public void run() {
        while (!quittingTime)
            pretendToWork();
        System.out.println("Beer is good");
    }
    private void pretendToWork() {
        try {
            Thread.sleep(300); // Sleeping on the job?
        } catch (InterruptedException ex) { }
    }

    // It's quitting time, wait for worker - Called by good boss
    synchronized void quit() throws InterruptedException {
        quittingTime = true;
        join();
    }
    // Rescind quitting time - Called by evil boss
    synchronized void keepWorking() {
        quittingTime = false;
    }

    public static void main(String[] args)
            throws InterruptedException {
        final Worker worker = new Worker();
        worker.start();

        Timer t = new Timer(true); // Daemon thread
        t.schedule(new TimerTask() {
            public void run() { worker.keepWorking(); }
        }, 500);

        Thread.sleep(400);
        worker.quit();
    }
}


import java.util.*; import java.lang.reflect.*;

public class Reflector {
    public static void main(String[] args) throws Exception {
        Set s = new HashSet();
        s.add("foo");
        Iterator it = s.iterator();
        Method m = it.getClass().getMethod("hasNext");
        System.out.println(m.invoke(it));
    }
}


public class Pet {
    public final String name;
    public final String food;
    public final String sound;

    public Pet(String name, String food, String sound) {
        this.name = name;
        this.food = food;
        this.sound = sound;
    }

    public void eat() {
        System.out.println(name + ": Mmmmm, " + food);
    }
    public void play() {
        System.out.println(name + ": " + sound + " " + sound);
    }
    public void sleep() {
        System.out.println(name + ": Zzzzzzz...");
    }

    public void live() {
        new Thread() {
            public void run() {
                while (true) {
                    eat();
                    play();
                    sleep();
                }
            }
        }.start();
    }

    public static void main(String[] args) {
        new Pet("Fido", "beef", "Woof").live();
    }
}


public class Outer {
    public static void main(String[] args) throws Exception {
        new Outer().greetWorld();
    }

    private void greetWorld() throws Exception {
        System.out.println(Inner.class.newInstance());
    }

    public class Inner {
        public String toString() {
            return "Hello world";
        }
    }
}


public class Greeter {
    public static void main (String[] args) {
        String greeting = "Hello world";
        for (int i = 0; i < greeting.length(); i++)
            System.out.write(greeting.charAt(i));
    }
}


public class BeerBlast {
    static final String COMMAND = "java BeerBlast slave";

    public static void main(String[] args) throws Exception {
        if (args.length == 1 && args[0].equals("slave")) {
            for (int i = 99; i > 0; i--) {
                System.out.println(i + " bottles of beer on the wall");
                System.out.println(i + " bottles of beer");
                System.out.println("You take one down, pass it around,");
                System.out.println((i-1) + " bottles of beer on the wall");
                System.out.println();
            }
        } else {
            // Master
            Process process = Runtime.getRuntime().exec(COMMAND);
            int exitValue = process.waitFor();
            System.out.println("exit value = " + exitValue);
        }
    }
}


public class CopyDog {
    public static void main(String[] args) {
        Dog newDog = ??? ; // You figure out what to put here

        // This line should print false
        System.out.println(newDog == Dog.INSTANCE);

        // This line should print "Woof"
        System.out.println(newDog);
    }
}

public class Dog extends Exception {
    public static final Dog INSTANCE = new Dog();
    private Dog() { }

    public String toString() {
        return "Woof";
    }
}


public class SelfInterruption {
    public static void main(String[] args) {
        Thread.currentThread().interrupt();

        if (Thread.interrupted()) {
            System.out.println("Interrupted: " + Thread.interrupted());
        } else {
            System.out.println("Not interrupted: " + Thread.interrupted());
        }
    }
}


public class Lazy {
    private static boolean initialized = false;

    static {
        Thread t = new Thread(new Runnable() {
            public void run() {
                initialized = true;
            }
        });
        t.start();
        try {
            t.join();
        } catch(InterruptedException e) {
            throw new AssertionError(e);
        }
    }

    public static void main(String[] args) {
        System.out.println(initialized);
    }
}


Java Puzzles: classier puzzlers


class Base {
    public String className = "Base";
}

class Derived extends Base {
    private String className = "Derived";
}

public class PrivateMatter {
    public static void main(String[] args) {
        System.out.println(new Derived().className);
    }
}


public class StrungOut {
    public static void main(String[] args) {
        String s = new String("Hello world");
        System.out.println(s);
    }
}

class String {
    private final java.lang.String s;

    public String(java.lang.String s) {
        this.s = s;
    }

    public java.lang.String toString() {
        return s;
    }
}


public class ShadesOfGray {
    public static void main(String[] args){
        System.out.println(X.Y.Z);
    }
}

class X {
    static class Y {
        static String Z = "Black";
    } 

    static C Y = new C();
}

class C {
    String Z = "White";
}


public class FadeToBlack {
    // This method should read and print the value of the field Z in class X.Y
    public static void main(String[] args){
    }
}

class X {
    static class Y {
        static String Z = "Black";
    } 

    static C Y = new C();
}

class C {
    String Z = "White";
}


package click;
public class CodeTalk {
    public void doIt() {
        printMessage();
    }

    void printMessage() {
        System.out.println("Click");
    }
}


package hack;
import click.CodeTalk;

public class TypeIt {
    private static class ClickIt extends CodeTalk {
        void printMessage() {
            System.out.println("Hack");
        }
    }

    public static void main(String[] args) {
        ClickIt clickit = new ClickIt();
        clickit.doIt();
    }
}


import static java.util.Arrays.toString;

class ImportDuty {
    public static void main(String[] args) {
        printArgs(1, 2, 3, 4, 5);
    }

    static void printArgs(Object... args) {
        System.out.println(toString(args));
    }
}


class Jeopardy {
    public static final String PRIZE = "$64,000";
}

public class DoubleJeopardy extends Jeopardy {
    public static final String PRIZE = "2 cents";

    public static void main(String[] args) {
        System.out.println(DoubleJeopardy.PRIZE);
    }
}


package client;

import library.Api;

/**
 * This class must make use of some member or constructor exported by
 * library.Api, such that this class (client.Client) compiles if and only if
 * the commented-out private declaration in the source file for library.Api
 * remains commented out.
 */
public class Client {

}


package library;

/**
 * This class may contain any desired code.  It must contain a commented-out
 * private declaration that causes the client (client.Client) to fail
 * to compile when uncommented. No prohibition is placed on what classes
 * or interfaces Api may extend or implement.
 */
public final class Api {

}


public class Conundrum {
    public static void main(String[] args) {
        Enigma e = new Enigma();
        System.out.println(e.equals(e));
    }
}

final class Enigma {
    // Provide a class body that makes Conundrum print false.
    // Do *not* override equals.
}


import java.util.Random;

public class CoinSide {
    private static Random rnd = new Random();

    public static CoinSide flip() {
        return rnd.nextBoolean() ? 
            Heads.INSTANCE : Tails.INSTANCE;
    }

    public static void main(String[] args) {
        System.out.println(flip());
    }
}

class Heads extends CoinSide {
    private Heads() { }
    public static final Heads INSTANCE = new Heads();

    public String toString() {
        return "heads";
    }
}

class Tails extends CoinSide {
    private Tails() { }
    public static final Tails INSTANCE = new Tails();

    public String toString() {
        return "tails";
    }
}


Java Puzzles: library puzzlers


import java.math.BigInteger;

public class BigProblem {
    public static void main(String[] args) {
        BigInteger fiveThousand  = new BigInteger("5000");
        BigInteger fiftyThousand = new BigInteger("50000");
        BigInteger fiveHundredThousand
                                 = new BigInteger("500000");

        BigInteger total = BigInteger.ZERO;
        total.add(fiveThousand);
        total.add(fiftyThousand);
        total.add(fiveHundredThousand);
        System.out.println(total);
    }
}


import java.util.*;

public class Name {
    private String first, last;

    public Name(String first, String last) {
        this.first = first;
        this.last = last;
    }

    public boolean equals(Object o) {
        if (!(o instanceof Name))
            return false;
        Name n = (Name)o;
        return n.first.equals(first) && n.last.equals(last);
    }

    public static void main(String[] args) {
        Set s = new HashSet();
        s.add(new Name("Mickey", "Mouse"));
        System.out.println(
            s.contains(new Name("Mickey", "Mouse")));
    } 
}


import java.util.*;

public class Name {
    private String first, last;

    public Name(String first, String last) {
        this.first = first; this.last = last;
    }

    public boolean equals(Name n) {
        return n.first.equals(first) && n.last.equals(last);
    }

    public int hashCode() {
        return 31 * first.hashCode() + last.hashCode(); 
    }

    public static void main(String[] args) {
        Set s = new HashSet();
        s.add(new Name("Donald", "Duck"));
        System.out.println(
            s.contains(new Name("Donald", "Duck")));
    }
}


import java.util.*;

public class Differences {
    public static void main(String[] args) {
        int vals[] = { 789, 678, 567, 456, 345, 234, 123, 012 };
        Set diffs = new HashSet();

        for (int i = 0; i < vals.length; i++)
            for (int j = i; j < vals.length; j++)
                diffs.add(vals[i] - vals[j]);
        System.out.println(diffs.size());
    }
}


import java.util.*;

public class OneLiners {
    public static void main(String[] args) {
        // Part A
        String[] breakfast = { "spam", "sausage", "spam", "spam", "bacon",
                               "spam", "tomato", "spam" };
        System.out.println(withoutDuplicates(Arrays.asList(breakfast)));

        // Part B
        String weaponry = "fear, surprise,ruthless efficiency, an almost " +
            "fanatical devotion to the Pope, nice red uniforms";
        System.out.println(Arrays.asList(parse(weaponry)));

        // Part C
        int[][] magic = {{6, 7, 2}, {1, 5, 9}, {8, 3, 4}};
        System.out.println(arrayToString(magic));

        // Part D
        System.out.println(hasMoreBitsSet(0x0f0f0f0f, 0x88888888)); // true
        System.out.println(hasMoreBitsSet(0x88888888, 0x0f0f0f0f)); // false
    }

    // Part A
    static  List withoutDuplicates(List original) {
        // Your code goes here
    }

    // Part B
    static String[] parse(String string) {
        // Your code goes here
    }

    // Part C
    static String arrayToString(Object[] array) {
        // Your code goes here
    }

    // Part D
    static boolean hasMoreBitsSet(int i, int j) {
        // Your code goes here
    }
}


import java.util.*;

public class DatingGame {
    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
        cal.set(1999, 12, 31); // Year, Month, Day
        System.out.print(cal.get(Calendar.YEAR) + " ");

        Date d = cal.getTime();
        System.out.println(d.getDay());
    }
}


import java.util.*;

public class NameGame {
    public static void main(String args[]) {
        Map m = new IdentityHashMap();
        m.put("Mickey", "Mouse");
        m.put("Mickey", "Mantle");
        System.out.println(m.size());
    } 
}


import java.util.*;

public class MoreNames {
    private Map m = new HashMap();

    public void MoreNames() {
        m.put("Mickey", "Mouse");
        m.put("Mickey", "Mantle");
    }

    public int size() {
        return m.size();
    }

    public static void main(String args[]) {
        MoreNames moreNames = new MoreNames();
        System.out.println(moreNames.size());
    } 
}


public class Mod {
    public static void main(String[] args) {
        final int MODULUS = 3;
        int[] histogram = new int[MODULUS];

        // Iterate over all ints (Idiom from Puzzle 25)
        int i = Integer.MIN_VALUE;
        do {
            histogram[Math.abs(i) % MODULUS]++;
        } while (i++ != Integer.MAX_VALUE);

        for (int j = 0; j < MODULUS; j++)
            System.out.println(histogram[j] + " ");
    } 
}


import java.util.*;

public class SuspiciousSort {
    public static void main(String[] args) {
        Random rnd = new Random();
        Integer[] arr = new Integer[100];

        for (int i = 0; i < arr.length; i++)
            arr[i] = rnd.nextInt();

        Comparator cmp = new Comparator() {
            public int compare(Integer i1, Integer i2) {
                return i2 - i1;
            }
        };
        Arrays.sort(arr, cmp);
        System.out.println(order(arr));
    }

    enum Order { ASCENDING, DESCENDING, CONSTANT, UNORDERED };

    static Order order(Integer[] a) {
        boolean ascending  = false;
        boolean descending = false;

        for (int i = 1; i < a.length; i++) {
            ascending  |= a[i] > a[i-1];
            descending |= a[i] < a[i-1];
        }

        if (ascending  && !descending)
            return Order.ASCENDING;
        if (descending && !ascending)
            return Order.DESCENDING;
        if (!ascending)
            return Order.CONSTANT;   // All elements equal 
        return Order.UNORDERED;      // Array is not sorted 
    } 
}


Java Puzzles: classy puzzlers


public class Confusing {
    private Confusing(Object o) {
        System.out.println("Object");
    }

    private Confusing(double[] dArray) {
        System.out.println("double array");
    }

    public static void main(String[] args) {
        new Confusing(null);
    }
}


class Counter {
    private static int count = 0;
    public static final synchronized void increment() {
        count++;
    }
    public static final synchronized int getCount() {
        return count; 
    } 
}

class Dog extends Counter {
    public Dog() { }
    public void woof() { increment(); }
} 

class Cat extends Counter {
    public Cat() { } 
    public void meow() { increment(); }
}

public class Ruckus {
    public static void main(String[] args) { 
        Dog dogs[] = { new Dog(), new Dog() };
        for (int i = 0; i < dogs.length; i++)
            dogs[i].woof();
        Cat cats[] = { new Cat(), new Cat(), new Cat() };
        for (int i = 0; i < cats.length; i++)
            cats[i].meow();
        System.out.print(Dog.getCount() + " woofs and ");
        System.out.println(Cat.getCount() + " meows");
    }
}


class Dog {
    public static void bark() {
        System.out.print("woof ");
    }
}

class Basenji extends Dog {
    public static void bark() { }
}

public class Bark {
    public static void main(String args[]) {
        Dog woofer = new Dog();
        Dog nipper = new Basenji();
        woofer.bark();
        nipper.bark();
    }
}


import java.util.Calendar;

public class Elvis {
    public static final Elvis INSTANCE = new Elvis();
    private final int beltSize;
    private static final int CURRENT_YEAR =
        Calendar.getInstance().get(Calendar.YEAR);

    private Elvis() {
        beltSize = CURRENT_YEAR - 1930;
    }

    public int beltSize() {
        return beltSize;
    }

    public static void main(String[] args) {
        System.out.println("Elvis wears a size " +
                           INSTANCE.beltSize() + " belt.");
    } 
}


public class Type1 {
    public static void main(String[] args) {
        String s = null;
        System.out.println(s instanceof String);
    }
}

public class Type2 {
    public static void main(String[] args) {
        System.out.println(new Type2() instanceof String);
    }
}

public class Type3 {
    public static void main(String args[]) {
        Type3 t2 = (Type3) new Object();
    }
}


class Point {
    protected final int x, y;
    private final String name; // Cached at construction time
    Point(int x, int y) {
        this.x = x;
        this.y = y;
        name = makeName();
    }

    protected String makeName() {
        return "[" + x + "," + y + "]";
    }

    public final String toString() {
        return name;
    }
}

public class ColorPoint extends Point {
    private final String color;
    ColorPoint(int x, int y, String color) {
        super(x, y);
        this.color = color;
    }

    protected String makeName() {
       return super.makeName() + ":" + color;
    }

    public static void main(String[] args) {
        System.out.println(new ColorPoint(4, 2, "purple"));
    }
}


class Cache {
    static {
        initializeIfNecessary();
    }

    private static int sum;
    public static int getSum() {
        initializeIfNecessary();
        return sum;
    }

    private static boolean initialized = false;
    private static synchronized void initializeIfNecessary() {
        if (!initialized) {
            for (int i = 0; i < 100; i++)
                sum += i;
            initialized = true;
        }
    }
}

public class Client {
    public static void main(String[] args) {
        System.out.println(Cache.getSum()); 
    } 
}



// This is meant to represent a library class. You must not modify it.
public class Thing {
    public Thing(int i) {
    }
}

public class MyThing extends Thing {
    private final int arg;

    /*
     * This constructor is illegal. Rewrite it so that it has the same
     * effect but is legal.
     */
    public MyThing() {
        super(arg = (int)System.currentTimeMillis());
    }
}


public class Null {
    public static void greet() {
        System.out.println("Hello world!");
    }

    public static void main(String[] args) {
        ((Null) null).greet();
    } 
}


public class Creator {
    public static void main(String[] args) {
        for (int i = 0; i < 100; i++)
            Creature creature = new Creature();
        System.out.println(Creature.numCreated());
    }
}

class Creature {
    private static long numCreated = 0;

    public Creature() {
        numCreated++;
    }

    public static long numCreated() {
        return numCreated;
    }
}


Java Puzzles: exceptional puzzlers


public class Indecisive { 
    public static void main(String[] args) {
        System.out.println(decision());
    }

    static boolean decision() {
        try {
            return true;
        } finally {
            return false;
        }
    } 
}


import java.io.IOException;

public class Arcane1 {
    public static void main(String[] args) {
        try {
            System.out.println("Hello world");
        } catch(IOException e) {
            System.out.println("I've never seen println fail!");
        }
    }
}

public class Arcane2 {
    public static void main(String[] args) {
        try {
            // If you have nothing nice to say, say nothing
        } catch(Exception e) {
            System.out.println("This can't happen");
        }
    }
}

interface Type1 {
    void f() throws CloneNotSupportedException;
}

interface Type2 {
    void f() throws InterruptedException;
}

interface Type3 extends Type1, Type2 {
}

public class Arcane3 implements Type3 {
    public void f() {
        System.out.println("Hello world");
    }

    public static void main(String[] args) {
        Type3 t3 = new Arcane3();
        t3.f();
    }
}


public class UnwelcomeGuest {
    public static final long GUEST_USER_ID = -1;

    private static final long USER_ID;
    static {
        try {
            USER_ID = getUserIdFromEnvironment();
        } catch (IdUnavailableException e) {
            USER_ID = GUEST_USER_ID;
            System.out.println("Logging in as guest");
        }
    }

    private static long getUserIdFromEnvironment() 
            throws IdUnavailableException { 
        throw new IdUnavailableException(); // Simulate an error
    }

    public static void main(String[] args) {
        System.out.println("User ID: " + USER_ID);
    }
}

class IdUnavailableException extends Exception { 
}


public class HelloGoodbye {
    public static void main(String[] args) {
        try {
            System.out.println("Hello world");
            System.exit(0);
        } finally {
            System.out.println("Goodbye world");
        }
    } 
}


public class Reluctant {
    private Reluctant internalInstance = new Reluctant();

    public Reluctant() throws Exception {
        throw new Exception("I'm not coming out");
    }

    public static void main(String[] args) {
        try {
            Reluctant b = new Reluctant();
            System.out.println("Surprise!");
        } catch (Exception ex) {
            System.out.println("I told you so");
        }
    }
}


import java.io.*;

public class Copy {
    static void copy(String src, String dest) throws IOException {
        InputStream in = null;
        OutputStream out = null;
        try {
            in = new FileInputStream(src);
            out = new FileOutputStream(dest);
            byte[] buf = new byte[1024];
            int n;
            while ((n = in.read(buf)) > 0)
                out.write(buf, 0, n);
        } finally {
            if (in != null) in.close();
            if (out != null) out.close();
        } 
    }

    public static void main(String[] args) throws IOException {
        if (args.length != 2)
            System.out.println("Usage: java Copy  ");
        else
            copy(args[0], args[1]);
    }
}


public class Loop {
    public static void main(String[] args) {
        int[][] tests = { { 6, 5, 4, 3, 2, 1 }, { 1, 2 },
                          { 1, 2, 3 }, { 1, 2, 3, 4 }, { 1 } };
        int n = 0;

        try {
            int i = 0;
            while (true) {
                if (thirdElementIsThree(tests[i++]))
                    n++;
            }
        } catch(ArrayIndexOutOfBoundsException e) {
            // No more tests to process
        }
        System.out.println(n);
    }

    private static boolean thirdElementIsThree(int[] a) {
        return a.length >= 3 & a[2] == 3;
    }
}


public class Thrower {
    public static void main(String[] args) {
        sneakyThrow(new Exception("This is a checked exception"));
    }

    /*
     * Provide a body for this method to make it throw the specified exception.
     * You must not use any deprecated methods.
     */
    public static void sneakyThrow(Throwable t) {

    }
}


class Missing {
    Missing() { }
}

public class Strange1 {
    public static void main(String[] args) {
        try {
            Missing m = new Missing();
        } catch (java.lang.NoClassDefFoundError ex) {
            System.out.println("Got it!");
        }
    }
}

public class Strange2 {
    public static void main(String[] args) {
        Missing m;
        try {
            m = new Missing();
        } catch (java.lang.NoClassDefFoundError ex) {
            System.out.println("Got it!");
        }
    } 
}


public class Workout {
    public static void main(String[] args) {
        workHard();
        System.out.println("It's nap time.");
    }

    private static void workHard() {
        try {
            workHard();
        } finally {
            workHard();
        }
    }
}


Java Puzzles: loopy puzzlers


class BigDelight {
    public static void main(String[] args) {
        for (byte b = Byte.MIN_VALUE; b < Byte.MAX_VALUE; b++) {
            if (b == 0x90)
                System.out.print("Joy!");
        }
    }
}


public class Increment {
    public static void main(String[] args) {
        int j = 0;
        for (int i = 0; i < 100; i++)
            j = j++;
        System.out.println(j);
    }
}


public class InTheLoop {
    public static final int END = Integer.MAX_VALUE;
    public static final int START = END - 100;

    public static void main(String[] args) {
        int count = 0;
        for (int i = START; i <= END; i++)
            count++;
        System.out.println(count);
    }
}


public class Shifty {
    public static void main(String[] args) {
        int i = 0;
        while (-1 << i != 0)
            i++;
        System.out.println(i);
    }
}


public class Looper {
    public static void main(String[] args) {
        // Place your declaration for i here

        while (i == i + 1) { 
        }
    }
}


public class BrideOfLooper {
    public static void main(String[] args) {
        // Place your declaration for i here

        while (i != i) { 
        }
    }
}


public class SonOfLooper {
    public static void main(String[] args) {
        // Place your declaration for i here

        while (i != i + 0) { 
        }
    }
}


public class GhostOfLooper {
    public static void main(String[] args) {
        // Place your declaration for i here

        while (i != 0)
            i >>>= 1;
    }
}


public class CurseOfLooper {
    public static void main(String[] args) {
        // Place your declarations for i and j here

        while (i <= j && j <= i && i != j) {
        }
    }
}


public class LooperMeetsWolfman {
    public static void main(String[] args) {
        // Place your declaration for i here

        while (i != 0 && i == -i) {
        }
    }
}


public class Count {
    public static void main(String[] args) {
        final int START = 2000000000;
        int count = 0;
        for (float f = START; f < START + 50; f++)
            count++;
        System.out.println(count);
    }
}


public class Clock {
    public static void main(String[] args) {
        int minutes = 0;
        for (int ms = 0; ms < 60*60*1000; ms++)
            if (ms % 60*1000 == 0)
                minutes++;
        System.out.println(minutes);
    }
}


Java Puzzles: puzzlers with character


public class LastLaugh {
    public static void main(String args[]) {
        System.out.print("H" + "a");
        System.out.print('H' + 'a');
    }
}


public class Abc {
    public static void main(String[] args) {
        String letters = "ABC";
        char[] numbers = { '1', '2', '3' };
        System.out.println(letters + " easy as " + numbers);
    }
}


public class AnimalFarm {
    public static void main(String[] args) {
        final String pig = "length: 10";
        final String dog = "length: " + pig.length();

        System.out.println("Animals are equal: "
                           + pig == dog);
    }
}


public class EscapeRout {
  public static void main(String[] args) {
    // \u0022 is the Unicode escape for double-quote (")
    System.out.println("a\u0022.length() + \u0022b".length());
  }
}


/**
 * Generated by the IBM IDL-to-Java compiler, version 1.0
 * from F:\TestRoot\apps\a1\units\include\PolicyHome.idl
 * Wednesday, June 17, 1998 6:44:40 o'clock AM GMT+00:00
 */
public class Test {
    public static void main(String[] args) {
        System.out.print("Hell");
        System.out.println("o world");
    }
}


public class LinePrinter {
  public static void main(String[] args) {
    // Note: \u000A is Unicode representation of linefeed (LF)
    char c = 0x000A;
    System.out.println(c);
  } 
}


\u0070\u0075\u0062\u006c\u0069\u0063\u0020\u0020\u0020\u0020
\u0063\u006c\u0061\u0073\u0073\u0020\u0055\u0067\u006c\u0079
\u007b\u0070\u0075\u0062\u006c\u0069\u0063\u0020\u0020\u0020
\u0020\u0020\u0020\u0020\u0073\u0074\u0061\u0074\u0069\u0063
\u0076\u006f\u0069\u0064\u0020\u006d\u0061\u0069\u006e\u0028
\u0053\u0074\u0072\u0069\u006e\u0067\u005b\u005d\u0020\u0020
\u0020\u0020\u0020\u0020\u0061\u0072\u0067\u0073\u0029\u007b
\u0053\u0079\u0073\u0074\u0065\u006d\u002e\u006f\u0075\u0074
\u002e\u0070\u0072\u0069\u006e\u0074\u006c\u006e\u0028\u0020
\u0022\u0048\u0065\u006c\u006c\u006f\u0020\u0077\u0022\u002b
\u0022\u006f\u0072\u006c\u0064\u0022\u0029\u003b\u007d\u007d


public class StringCheese {
    public static void main(String args[]) {
        byte bytes[] = new byte[256];    
        for(int i = 0; i < 256; i++)
            bytes[i] = (byte)i;
        String str = new String(bytes);
        for(int i = 0, n = str.length(); i < n; i++)
            System.out.print((int)str.charAt(i) + " ");
    }
}


public class Classifier {
    public static void main(String[] args) {
        System.out.println(
            classify('n') + classify('+') + classify('2')); 
    }

    static String classify(char ch) {
        if ("0123456789".indexOf(ch) >= 0)
            return "NUMERAL ";
        if ("abcdefghijklmnopqrstuvwxyz".indexOf(ch) >= 0)
            return "LETTER ";
/*
 *      (Operators not supported yet) 
 *      if ("+-*/&|!=".indexOf(ch) >= 0)
 *          return "OPERATOR "; 
 */
        return "UNKNOWN "; 
    } 
}


package com.javapuzzlers;

public class Me {
   public static void main(String[] args) {
      System.out.println(
         Me.class.getName().replaceAll(".", "/") + ".class");
   }
}


package com.javapuzzlers;
import java.io.File;

public class MeToo {
    public static void main(String[] args) {
    System.out.println(MeToo.class.getName().
        replaceAll("\\.", File.separator) + ".class");
  }
}


public class BrowserTest {
    public static void main(String[] args) {
        System.out.print("iexplore:");
        http://www.google.com;
        System.out.println(":maximize"); 
    }
}


import java.util.*;

public class Rhymes {
    private static Random rnd = new Random();

    public static void main(String[] args) {
        StringBuffer word = null;
        switch(rnd.nextInt(2)) {
            case 1:  word = new StringBuffer('P');
            case 2:  word = new StringBuffer('G');
            default: word = new StringBuffer('M');
        }
        word.append('a');
        word.append('i');
        word.append('n');
        System.out.println(word);
    }
}


Java Puzzles: Expressive Puzzlers


public class Tweedledee {
    public static void main(String[] args) {
        // Put your declarations for x and i here

        x = x + i;  // Must be LEGAL
        x += i;     // Must be ILLEGAL
    }
}


public class Elementary {
    public static void main(String[] args) {
        System.out.println(12345 + 5432l);
    }
}


public class JoyOfHex {
    public static void main(String[] args) {
        System.out.println(
            Long.toHexString(0x100000000L + 0xcafebabe));
    }
}


public class Multicast {
    public static void main(String[] args) {
        System.out.println((int) (char) (byte) -1);
    }
}


public class CleverSwap {
    public static void main(String[] args) {
        int x = 1984;
        int y = 2001;
        x ^= y ^= x ^= y;
        System.out.println("x = " + x + "; y = " + y);
    }
}


public class DosEquis {
    public static void main(String[] args) {
        char x = 'X';
        int i = 0;
        System.out.print(true  ? x : 0);
        System.out.print(false ? i : x); 
    }
}


public class Tweedledum {
    public static void main(String[] args) {
        // Put your declarations for x and i here

        x += i;     // Must be LEGAL
        x = x + i;  // Must be ILLEGAL
    }
}


Java Puzzles


Puzzle# 1:
public class Oddity {
    public static boolean isOdd(int i) {
        return i % 2 == 1;
    }

    public static void main(String[] args) {

    }
}


Puzzle# 2:
public class Change {
    public static void main(String args[]) {
        System.out.println(2.00 - 1.10);
    }
}


Puzzle# 3:
public class LongDivision {
    public static void main(String[] args) {
        final long MICROS_PER_DAY = 24 * 60 * 60 * 1000 * 1000;
        final long MILLIS_PER_DAY = 24 * 60 * 60 * 1000;

        System.out.println(MICROS_PER_DAY / MILLIS_PER_DAY);
    }
}


For more exciting puzzles and descriptive insight please see Java Puzzler book by Joshua Bloch and Neal Gafter

A Brief History of the (Java) World and a Peek Forward


 
Neal Gafter reviews the long history of Java from its inception to the present and makes an incursion into what he thinks will be a great future and guessing what might come in Java SE 9+ after 2014. 



Notes:
Neal Gafter & Joshua Bloch wrote a book together named "Java Puzzlers"

Tuesday, September 13, 2011

Spring: MVC 3 Showcase: Git, Maven & Eclipse

Step by Step Guide to import 'Spring MVC 3 Showcase' sample from Git repository into Eclipse with Maven

This page is put together to facilitate those folks who are facing some issues running & integrating Springsource Spring MVC showcase sample code into eclipse with maven.



Step1: Get the code
Option1: 
download code by clicking download link from https://github.com/SpringSource/spring-mvc-showcase

Option2: 
Clone from Git repository via Git command line as follows

$ git clone git://github.com/SpringSource/spring-mvc-showcase.git

If this is your first time using Github, review http://help.github.com to learn the basics.

Option3: 
Clone from Git repository via EGit plugin for eclipse 
For installation instruction and usage for Egit plugin see this tutorial which gives nice overview.

Step2: Import the code into Eclipse

In eclipse click File and then Import...
Select "Existing Maven Project" as below

Note: If you don't see "Maven" category in Import dialog above consider downloading m2e (M2Eclipse) plugin for eclipse
Now Provide the location of downloaded code repository and then click Finish




This will import nice Maven project into eclipse but this is not ready yet to test within eclipse using tomcat. In order to deploy this project into Tomcat within Eclipse the project has to be a "Web Project" in nature. This imported project is just a Java Project with Maven support in eclipse.

Let make this project a "Web Project" as follow


Step3: Convert Project into Web Project


Right click on the spring-mvc-showcase project in eclipse and then Properties

Then Select "Project Facets" as below...


As you can see this project is not yet configured to use facets. lets click on the link "convert to faceted form..." as in the above dialog box


Now select "Dynamic Web Module" from Project Facets and then Click on the Link "Further configuration available" link at the bottom as per the below screenshot


Now change "Content directory" of Web Module to "/src/main/webapp" to comply with Maven structure.


Also select "Apache Tomcat..." from Runtimes tab on the right column as above screen.
Click OK to finish configuring project facets and converting our project to a dynamic web project.




Now this project is ready to be deployed into tomcat within eclipse.
Right click on the project and select Run as --> Run on server
Select Tomcat and click Finish as below screen


At this stage the project should be added and deployed to Tomcat server and could be accessed via URL http://localhost/spring-mvc-showcase/


Note: In my case I got the below error while Tomcat's attempt to deploy the application. I thought its worth mentioning, may be this help others to resolve the same issue



SEVERE: Error configuring application listener of class org.springframework.web.context.ContextLoaderListener
java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener
	at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1664)
	at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1509)
	at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:406)
	at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:388)
	at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:117)
	at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4268)
	at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:4771)
	at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:138)
	at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:990)
	at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:772)
	at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:138)
	at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:990)
	at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:275)
	at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:138)
	at org.apache.catalina.core.StandardService.startInternal(StandardService.java:424)
	at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:138)
	at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:648)
	at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:138)
	at org.apache.catalina.startup.Catalina.start(Catalina.java:576)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
	at java.lang.reflect.Method.invoke(Method.java:597)
	at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
	at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:415)
Sep 12, 2011 2:37:04 AM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Skipped installing application listeners due to previous error(s)
Sep 12, 2011 2:37:04 AM org.apache.catalina.core.StandardContext startInternal
SEVERE: Error listenerStart
Sep 12, 2011 2:37:04 AM org.apache.catalina.core.StandardContext startInternal
SEVERE: Context [/spring-mvc-showcase] startup failed due to previous errors

So this suggests that Tomcat could not find Spring's ContextLoaderListner class. which is kinda odd. lets see whats happening under the hood.
As all our project dependencies are handled by Maven we should not be worried about handling & deploying dependencies into Tomcat (servlet container) within eclipse. Lets first check we have spring related dependencies added to the Maven POM file.
Now as we see that pom.xml already contains spring dependencies, the next clue which comes into mind is that to check deployment assembly of the project and make sure Maven Libraries are included.

Right click on the project, then "Properties"
Now check "Deployment Assembly"
Yups, that was the issue.... Maven Dependencies were missing from Deployment Assembly.


Lets add Maven Library into Deployment Assembly as below screen



Click Apply and OK

Now lets restart the application by right clicking on the tomcat server and then click "Restart"
This should work now but again in my case with Tomcat version 7, I got below error...



SEVERE: Servlet.service() for servlet jsp threw exception
org.apache.jasper.JasperException: Unable to read TLD "jndi:/localhost/spring-mvc-showcase/WEB-INF/lib/jstl-impl-1.2.jar" from JAR file "jndi:/localhost/spring-mvc-showcase/WEB-INF/lib/jstl-impl-1.2.jar": org.apache.jasper.JasperException: Failed to load or instantiate TagLibraryValidator class: org.apache.taglibs.standard.tlv.JstlCoreTLV
	at org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:51)
	at org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:409)
	at org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:181)
	at org.apache.jasper.compiler.TagLibraryInfoImpl.(TagLibraryInfoImpl.java:179)
	at org.apache.jasper.compiler.Parser.parseTaglibDirective(Parser.java:387)
	at org.apache.jasper.compiler.Parser.parseDirective(Parser.java:451)
	at org.apache.jasper.compiler.Parser.parseElements(Parser.java:1401)
	at org.apache.jasper.compiler.Parser.parse(Parser.java:130)
	at org.apache.jasper.compiler.ParserController.doParse(ParserController.java:238)
	at org.apache.jasper.compiler.ParserController.parse(ParserController.java:101)
	at org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:198)
	at org.apache.jasper.compiler.Compiler.compile(Compiler.java:360)
	at org.apache.jasper.compiler.Compiler.compile(Compiler.java:340)
	at org.apache.jasper.compiler.Compiler.compile(Compiler.java:327)
	at org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:594)
	at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:314)
	at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:320)
	at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:265)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
	at ....

Now this time the issue is different.
As we already checked that the Maven dependencies are already there but why Tomcat is complaining Failed to load instance of TagLibrary.

I suspect there might be a conflict in the libraries. lets compared the default Tomcat's (version 7 in my case) loaded libraries with Maven Libraries.

Got it, we have a duplicate library loaded named "jsp-api-2.1.jar" in Maven pom.
Lets exclude it by right clicking on the above duplicate library in the Maven dependency tree and select Maven-->Exclude Maven Artifact...

Restart Tomcat one more time.
Congratulations!, we got the "spring-mvc-showcase" application working.... 
successfully deployed to Tomcat version 7 within eclipse.

I hope this help some folks who are trying hard to get started with spring-mvc and related tools like GIT etc with eclipse.
Happy coding and exploring the world of SpringMVC!!!


Note: Here is the link to Spring MVC3-showcase blog