Sep 23, 2013

Java Puzzle #1

Inspired by Java Puzzlers conference, spotted interesting behaviour of following code:
public class LongNull {
    Long longi = null;

    public long getLongi() {
        return longi;

    public static void main(String[] args) {
        System.out.println(new LongNull().getLongi());
What it produces:
  1. NullPointerException
  2. Prints 0
  3. Prints null
Answer is 1. NullPointerException during auto unboxing. Change getLongi() to return Long instead of long fixes this and output will be 'null'.

No comments: