Sunday, March 28, 2010

Java Puzzlers

Borrowed from Java Puzzlers. An awesome book BTW!!
Guess the output of the two programs below:

1.
public class SetTest {

    public static final String[] URLNAMES =  {
        "http://javapuzzlers.com",
        "http://apache2-snort.skybar.dreamhost.com",
        "http://www.google.com",
        "http://javapuzzlers.com",
        "http://findbugs.sourceforge.net",
        "http://cs.umd.edu"
    };

    public static void main(String[] args) throws MalformedURLException {
        Set favourites = new HashSet();

        for (String names : URLNAMES) {
            favourites.add(new URL(names));
        }
        System.out.println("Size is : " + favourites.size());
    }
}

2.
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.");
    }
}

Output 1:
Prints 4, if connected to internet and 5 else!! :) Checks for host names and in turn IP addresses for the site names entered as URL objects. Apparently, first and second strings resolve to same IP address. (Haven't verified it though, trusting the author!). URL equal() and hashcode() methods are broken, so, instead use URI objects and URI.create() method to create objects!

Output 2:
-1930
Initializing sequence when an object is created. First, static fields get default values, so INSTANCE defaulted to null and CURRENT_YEAR defaulted to 0. Then static initializers get called, accordingly, new Elvis() gets executed and beltsize gets initialized to 0-1930 = -1930!!!! Hence, the output..

No comments:

Post a Comment