Why the following code does not compile ?

R

Razvan

Hi !




The following code does not compile:

byte bb = 7;
bb = bb + ((byte) 5);

Since both operands are bytes there should be no problem, yet
there is a "possible loss of precision" !




Regards,
Razvan
 
A

Adam Maass

Razvan said:
Hi !




The following code does not compile:

byte bb = 7;
bb = bb + ((byte) 5);

Since both operands are bytes there should be no problem, yet
there is a "possible loss of precision" !

The addition is int arithmetic. The result of the addition is an int.


-- Adam Maass
 
P

Paul Lutus

Razvan said:
Hi !




The following code does not compile:

byte bb = 7;
bb = bb + ((byte) 5);

Since both operands are bytes there should be no problem, yet
there is a "possible loss of precision" !

The operator "+" assumes integer operands in this case. Use:

bb = (byte) (bb + 5);
 
S

Superdude

Razvan said:
Hi !




The following code does not compile:

byte bb = 7;
bb = bb + ((byte) 5);

Since both operands are bytes there should be no problem, yet
there is a "possible loss of precision" !




Regards,
Razvan

any mathematical operation is at minimum an int result unless any of the
operands are long, float, double, then the result is the highest bit size.
 
B

Babu Kalakrishnan

ANOOP said:
try this....

byte bb = 7;
bb = (byte) (bb + ((byte) 5));

or simply :

bb += 5;

The cast to (byte) is implicitly performed when you use the
+= operator.

BK
 
B

Babu Kalakrishnan

Razvan said:
byte bb = 7;
bb = bb + ((byte) 5);

Since both operands are bytes there should be no problem, yet
there is a "possible loss of precision" !

Both operands being bytes does not mean that the result would fit into a
byte. (Try adding two bytes with values >= 64)

BK
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,045
Latest member
DRCM

Latest Threads

Top