Java5 autoboxing


A new feature of java5 is autoboxing, which automatically converts between primitives and its wrapper types. This may be very handy, but can also be a source for a severe headache.
I was creating a unittest to compare two double values. I was not using and IDE so I just implemented it as: assertEquals (String, double, double) as I would do when comparing Strings, Objects, int’s etc. When I ran the the test, using Ant and java5, all went fine. I then deployed the code on one of our classroom PC’s, with Java1.4.2, and suddenly the code didn’t compile anymore. It failed with the error message: ‘cannot find symbol – symbol : method assertEquals(java.lang.String,double,double)’.

It finally realized that the assertEquals (String, double, double) method does not exist, it must have an extra, double, parameter that indicates the allowed delta (to indicate the precision). But I failed to understand why this would be allowed in Java5 and not in java1.4.x. Finally, when working in an IDE I realized that, thanks to java5 autoboxing ;-(, I was using the assertEquals (String, Object, Object) method which is a very valid (and functioning) method (but actually not really the method that I needed). But since java1.4 is not able to do such a conversion it fails to find a matching method and will fail on compilation.
By the way, it is quite easy to change the behavior of the java5 compiler, e.g. by adding source=”1.4″ to the javac ant task. Also Eclipse (and certainly the other IDE’s as well ) can change the compiler compliance level. It is probably even better to have the IDE warn you for these issues, but unfortunately in Eclipse the default level is ‘ignore’ for this specific case. And off course, this won’t help you when you’re not using an IDE.


About Author

Aino Andriessen is a consultant on Enterprise Java, ADF, PL/SQL, XML, and SOA development and is Expertise Lead on Application Lifecycle Management (ALM). He has a strong interest in ADF, SOA, Maven, architecture, quality management, delivery and application lifecycle management. Aino publishes on the AMIS technology blog and has been a presenter at the ODTUG Kaleidoscope, Oracle Open World and UKOUG TechEbs.

1 Comment

  1. Rob van Maris on

    Good point to be aware of this caveat, but cause for a severe headache I’d say? After all, the 1.5 compiler compiles your code exactly as you intended, and the 1.4 compiler produces a clear errormessage. The bytecode produced by the 1.5 compiler would even have run on the 1.4 JVM.
    Lesson learned is that code using 1.5′s new language features does not compile on a 1.4 compiler – hardly supprising. Your story demonstrates that one can be using such a feature (auto-boxing) without being aware of it!