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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Tim Cooke
• Devaka Cooray
• Ron McLeod
• Jeanne Boyarsky
Sheriffs:
• Liutauras Vilda
• paul wheaton
• Junilu Lacar
Saloon Keepers:
• Tim Moores
• Stephan van Hulst
• Piet Souris
• Carey Brown
• Tim Holloway
Bartenders:
• Martijn Verburg
• Frits Walraven
• Himai Minh

# Primitive Assignments

Greenhorn
Posts: 11
• Number of slices to send:
Optional 'thank-you' note:
Line 1 : byte a = 3;
Line 2 : a+= 7L;

The compiler automatically puts a cast in line 1. Will the second line run fine or will it require an explicit cast?
In case we require an explicit cast for long to byte (even though after the addition the value will easily fit into a byte), why don't we require an explicit cast in line 1 where also we are narrowing??

Ranch Hand
Posts: 808
1
• Number of slices to send:
Optional 'thank-you' note:
byte a = 3;
a += 7L;

is equivalent to:
byte a = 3;
a += (byte)7L;

But:
byte a = 3;
a = a + 7L; //compiler error

+= operator makes implicit cast

Pooja Sinha
Greenhorn
Posts: 11
• Number of slices to send:
Optional 'thank-you' note:
In that case,

Why does byte a = 3 work fine but not byte a = 7L?

Why does the compiler automatically casts the first expression and not the second?

Lucas Smith
Ranch Hand
Posts: 808
1
• Number of slices to send:
Optional 'thank-you' note:
Look at the Java Language Specification - long has special treatment.

Ranch Hand
Posts: 196
• Number of slices to send:
Optional 'thank-you' note:

Lukas Smith wrote:
+= operator makes implicit cast

Not only +=, all extended assignment operators put in an implicit cast..........

Lucas Smith
Ranch Hand
Posts: 808
1
• Number of slices to send:
Optional 'thank-you' note:
It's logical.

karthick chinnathambi
Ranch Hand
Posts: 196
• Number of slices to send:
Optional 'thank-you' note:

Lukas Smith wrote:It's logical.

s my friend........

just wanted to mention that point.......

Sheriff
Posts: 9697
43
• Number of slices to send:
Optional 'thank-you' note:

karthick chinnathambi wrote:
s my friend........

What's "s"?? is it yes?? if yes, then try to Use Real Words when you post anything...