Tuesday, February 15, 2011

A Bite at Java Bytes

After using Java for so long, I'm still surprised that you can't write something like:-

public byte addNums(byte a, byte b) {
return a+b;

// Call the function:-
addNums(1, 2); // Get a compiler error??

The compiler error is because the 1 and 2 are ints by default, and the function is expecting bytes. Surely it must be able to work out that 1 and 2 are bytes in this case, not ints? To get it to compile you need to write:-

addNums((byte)1, (byte)2); // Get a compiler error??

I don't normally mind verbose code as long as it adds information for the programmer, but this is pointless.

No comments: