Archive

Posts Tagged ‘interview’

Java Interviews and trick questions

September 28th, 2009 16 comments

java_interviewI have taken many java interviews over the last few years. As time passed by, I learned from mistakes I have made. One of them being to ask candidates trick questions or questions that do not necessarily have an obvious answer.

I read a blog post recently that detailed such a question. I will highlight the question here along with the answer

public class JavaPuzzler{
    public static void main(String[] args) {
        HashSet<Short> s = new HashSet<Short>();//1
        for(short i = 0; i<100;i++){//2
            s.add(i);//3
            s.remove(i-1);//4
        }
        System.out.println(s.size());//5
    }
}

Can you guess the answer to this question ? Simply drag and select the text near the spoiler to see the answer.

Spoiler: The answer to the question is 100. The gotcha is that the statement s.remove(i-1); at //4 will autobox to an Integer and not a Short. Equals comparison between an Integer and Short fails.

Categories: java Tags: , ,