programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Help with Mathematical operation on bytes

Abhishek Chhawcharia
Greenhorn
Posts: 11
Hi All,

byte a1 = 0;
byte a2 = 4
byte a3 = 4;

//below statement gives a compilation error
a1 = a2 + a3;

//below line compiles fine.
a1 = 4 + 4;

Can someone explain me why?

Henry Wong
author
Sheriff
Posts: 23295
125
• 4
Abhishek Chhawcharia wrote:
//below statement gives a compilation error
a1 = a2 + a3;

//below line compiles fine.
a1 = 4 + 4;

Can someone explain me why?

The rules are kinda complicated on this -- so much so, that I don't know how to give a hint... so, here is the reason.

1. The "4" is a literal integer, and a compile time constant.

2. The "4 + 4" is an expression of literals, and interestingly, based on the rules, is still a compile time constant.

3. The a2 is not a compile time constant. And the a3 variable is also not a compile time constant.

4. The "a2 + a3" is an expression, and based on the rules, is *not* a compile time constant. It is also of type integer.

So...

The "a1 = a2 + a3;" expression is not allowed, because you are trying to assign an integer to a byte, and that is not allowed to be done with an implicit cast.

The "a1 = 4 + 4;" expression is also trying to assign an integer to a byte. However, there is a special rule regarding assignments and compile time constants. When doing that, and the compiler is able to determine that the value of the integer (RHS) can fit into the byte (LHS), then the assignment is allowed.

Henry

Mark King
Ranch Hand
Posts: 55
When you add two bytes together the compiler converts both to ints and performs integer arithmetic therfore line 1 results in int which causes a type mismatch.

In line 2 the compiler can see that the results fit in a byte so it does not complain. In line 1 you use variables and the compiler does not know at compile time what the values of the variables are (since you can change them wherever you want), therefore the compiler complains.

If you use final variables the compiler will be able to determine that the result will fit into a byte and your code will compile.

Stevens Miller
Bartender
Posts: 1445
30
• 1
You can "downcast" the integer created by adding two native byte variables to a byte, like this:

But watch out, as this isn't always going to do what you might expect. For example, what do you think this will print?

 Did you see how Paul cut 87% off of his electric heat bill with 82 watts of micro heaters?