programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Liutauras Vilda
• Devaka Cooray
• Jeanne Boyarsky
• Bear Bibeault
Sheriffs:
• Junilu Lacar
• Paul Clapham
• Knute Snortum
Saloon Keepers:
• Ron McLeod
• Tim Moores
• Stephan van Hulst
• salvin francis
• Carey Brown
Bartenders:
• Tim Holloway
• Frits Walraven
• Ganesh Patekar

# Interesting problem with byte

Ranch Hand
Posts: 134
Hi

Following code explains my problem.

Isnt the 1st stmt same as the 2nd/3rd stmt? If not, why?

Ashish

Ranch Hand
Posts: 79
Hi!

I haven't check this from specs, but i think that -1 is assumed to be int, so what compiler real tries to do, is following:

a *= (int) -1;

try this: a *= (byte) -1;

- artsi

Greenhorn
Posts: 2
Hi,
This is one of the advantages of the Compound Assignment Operator +=

When you do any integer arithmetic with byte values, the compiler expects you to put an explicit cast before assigning the result to a byte variable.

For example,
byte a = 3;
a = a + 5; //won't compile,
//needs an explicit cast a = (byte) a + 5;

But when you do the same thing with Compound Assignment operator,We are ensuring the Compiler that the resulting value will definitely fit to a byte variable.
See this,
byte a = 3;
a += 5; //Compiles without any error.

Thanks,
Sathya.

Wanderer
Posts: 18671
Isnt the 1st stmt same as the 2nd/3rd stmt? If not, why?

No. Compound assignment operators (+=, -=, *=, etc.) do more than just perform the operation and assign the result to the variable on the left - they also insert a cast to whatever type the variable on the left has. So

a *= -11;

is equivalent to

a = (int) (a * -1);

Similarly,

a += b;

is equivalent to

a = (int) (a + b);

(Assuming a and b are ints.)

Ranch Hand
Posts: 3178

Originally posted by Ashish Chopra:

Isnt the 1st stmt same as the 2nd/3rd stmt? If not, why?

No, the first statement is not the same as the second and the third, because we cannot terminate a statement without a semicolon( behind it... I don't see semicolons behind those lines, except the first line... So the compilation fails...

Ashish Chopra
Ranch Hand
Posts: 134
thanx a lot guys....my doubt stands cleared.

Ranch Hand
Posts: 45
hi guys,
are we sure we are getting the same error

Cant convert byte to int

because when i compile i get the following error

for the following code

nischal

Ashish Chopra
Ranch Hand
Posts: 134
i tried out the code that u mentioned.
It still gave me the error saying: cannot convert int to byte.

Though I am using eclipse IDE ...