Archive

Posts Tagged ‘puzzle’

Is ‘final’ keyword always safe to add/remove?

January 14th, 2011 8 comments

If somebody asked me this question “Is it always safe to put/remote ‘final’ keyword on a read only local variable?”, honestly I would have answered “Yes”.

Until I read JavaPuzzlers by Joshua Bloch and Neal Gafter and realized what a little variant of puzzle #8 would look like:

What’s the output of this code?

public static void main(String[] args)
{
    int z1 = 0;
    final int z2 = 0;

    System.out.println(false ? z1 : 'X');
    System.out.println(false ? z2 : 'X');
}
Tags: ,

Wednesday night puzzle

December 8th, 2010 2 comments

What’s the result of running this piece of code?

a) Done.
b) InterruptedException is thrown
c) It depends
d) Code doesn’t compile

import java.util.Vector;

public class Main {
  interface A {
  }
  
  static class AImpl implements A {
    static AImpl DUMMY = new BImpl();
  }

  interface B extends A {
  }

  static class BImpl extends AImpl implements B {
  }

  public static void main(String[] args) throws InterruptedException {
    final Vector<Object> values = new Vector<Object>();

    Thread thread = new Thread() {
      @Override
      public void run() {
        values.add(AImpl.DUMMY);
      }
    };
    thread.start();
    values.add(new BImpl());
    thread.join();

    System.out.println("Done.");
  }
}
Tags: ,