Tuesday, October 6, 2009

It's all C's fault: Part II

In a previous post, I vented about the ambiguity of expressions such as (a)-b. Are we subtracting (a) from b, or are we casting -b to type a? I have news: the Java compiler struggles with this same problem.

Integer i1 = (int)3; // valid
Integer i2 = (int)-3; // valid
Integer i3 = (int)-(3); // valid
Integer i4 = (Integer)3; // valid
Integer i5 = (Integer)-3; // compile error
Integer i6 = (Integer)-(3); // compile error
Integer i7 = (Integer)(-3); // valid

There's some automatic boxing of primitive types into wrapper types going on here, a feature of Java 5. The fact that the compiler can handle 3 but not -3 in any particular location is to me a fault. This is with jdk1.5.0_16.

At least I've got evidence that the (Type)expression casting syntax is troublesome.


Andy said...

I didn't believe you that it was a big deal, but I guess you were right.

Jordan said...

I think it is beneficial to wrap these primitive types though. Wrappers > primitive types. Although, I can see your point. Very troublesome indeed.