Monday, November 26, 2012

Compilation Error: Byte Operations b = b + 1

Yet we have worked so much in Java, but still we are not aware all intricacies of the languages. Even after knowing so much it seems comes up with something new to astonish me. It is like a disillusion charm, which keeps me under the covers.

Here we are talking about byte operations.

Create a class and type the following lines in a method.

byte b = 0;
b++;
b = b + 1;

Now you will realize eclipse shows a compile time error, but why it is not a consistent behavior between line 2 and line 3.

But we must understand the difference between these 2 operations.
Though in theory b++, b+1 are same statement, but for compiler those are not same statement. 

In case of b++, compiler knows the value of b and internally it is adding 1, whereas b + 1 is operation between a byte and an integer. Though 1 is constant, but compiler understands it as integer.

So we can make some change in code and it should work.

byte b = 0;
b++;
b = b + (byte) 1;

Still it is a compile time error. Now what? I have converted 1 to byte and I am adding 2 bytes, now what is the problem.

So the problem is compiler. For these operations(+ , -, *) it uses 4 bytes atleast, i.e. minimal results of these operations is int.

So b + (byte) 1; still results in integer, which must be type-casted to byte. So following code will work perfectly fine.

byte b = 0;
b++;
b = (byte) (b + 1);

If you finalize the byte variable, then it is possible to add two bytes without typecasting.

final byte b = 117;
final byte c = 10;
byte d = b + c;

In this case b, and c are constants and they values will not change after this operations. So compiler know that d = 127 which is maximum allowable byte. So it works without causing any issue.


final byte b = 118;
final byte c = 10;
byte d = b + c;

But at this time compilation fails as 128 is an integer not a byte, so compiler needs explicit downcast.


final byte b = 117;
final byte c = 10;
byte d =(byte)( b + c);

Byte operations and questions are tricky so keep such things in mind before answering them in interviews. I could not find the reference, but will post that reference soon.

No comments:

Post a Comment