Sunday, June 14, 2009

Puzzle 32 – Solution

The solution to this puzzle lies in the way packages work in Java. The key concept behind packages is that more than one class can share the same name as long as they belong to different packages.

The code snippet that does the trick is,

package com.twister;

class String{}

public class DoubleTrouble{
public static void main(String args[])
"This is the wrong one!");}
public static void main(java.lang.String args[])
"This is the right one!");}

The class String in the same package takes precedence over the class java.lang.String. Fully qualifying the method which prints "This is the right one" with java.lang.String does the trick!

The were a couple of other really good solutions -
1.Putting the invalid main in a inner class or altogether different class.
2. Having a static initialization block. No one said that "This is the wrong one" should not print when the code is run - just that "This is the right one!" should.
Having a static block does that - innovative!

Puzzle 15 is based on the same concept but is worded differently!!

No comments:

Post a Comment

Solution for this question?