Monday, March 29, 2010

Use Java Generics ...

I sense that the world of Java developers is rather divided on this, but it is imperative that you understand and use Java Generics effectively. Pick up the very readable Naftalin/Wadler book, Gilad Bracha's introductory paper on java.sun.com and try to read the gist of Angelika Langer's FAQ to get to the bottom of it. Do it now.

There is no provision for this post if above is the only thing it were to say. Google is there to help you find these references. I wanted to point out a minor advantage of using Generics in Java code. All the major advantages like catching the errors as soon as you make them is covered nicely in the above references. Here is that minor time-saver:

If you use raw collections (e.g. List and not List<String>), it is rather time-consuming to find what they contain.
Of course, one could argue that one should check Javadocs for that. But in a state-of-the-art IDE like IDEA and a modularized build, you generally tend to look at the source and in deeply rooted call trees, it is not immediately clear instances of what type are added to a List. So, consider using generic types.

Wednesday, March 3, 2010

An Original Java Puzzler ...

Without further ado, what will be the output of the following program:

1 class ClassClass {
2 public static void main(String... args) {
3 System.out.println("Is Object.class instanceof Object?: " + Object.class instanceof Object);
4 System.out.println("Is Object.class instanceof Class?: " + Object.class instanceof Class);
5 }
6 }

Of course, I don't know if it is original or not. But I ran into it myself and thought of making it a puzzler :). Here are the options:
  1. Is Object.class instanceof Object?: false
    Is Object.class instanceof Class?: true
  2. Is Object.class instanceof Object?: true
    Is Object.class instanceof Class?: true
  3. Compiler error on line number 4
  4. Compiler error on both lines: 3 and 4
See first comment for answers.