• Post Reply Bookmark Topic Watch Topic
  • New Topic
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
  • paul wheaton
  • Paul Clapham
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Roland Mueller
  • Piet Souris
Bartenders:

k&b Operators and Assignment Doubt

 
Ranch Hand
Posts: 243
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Ranchers,

On page 148,Ch-3 ,Operators and assignment it is given that


byte b=27;
but only....,the compiler puts in the cast,the preceding code is identical to the following
byte b=(byte)27;



Now on page 149,last line


byte a=128;//byte can only hold up to 127



And continuing on Page 150,


We can fix it with the cast
byte a=(byte)128;



Ok..,i know that
byte b=27;
byte b=(byte)128;
will compile

but this will not
byte b=128;

but according to the first quote mentioned from k&b,as the book says,doing
byte b=128;
should also have an implicit cast like byte b=(byte)128; when
byte b=27;
is having an implicit cast.
and thus byte b=128; should also compile and run.

i know cast will not be needed in the range of the primitive but here
in the book they have not mentioned it???

Thanks,
Anand
 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Anand,

The compiler doesnt narrow down a value unless you mention it otherwise which requires *explicit* type casting to truncate bits. If without tinkering with the *value*, the compiler can assign an *int* literal to a *byte* then it would go a head and do it without cribbing but if the left hand literal doesnt fit in the Right hand variable then it would throw a compilation error in doing the same.

Hope this help.
Kunal
 
Ranch Hand
Posts: 335
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
three condition for implicit narrowing conversion during assignment

source is of byte, short, char or int
destination is of type byte,short,char
value of source is in range with destination at compile time

if all above conditions met than imlicit narrowing conversion allowed at assignment time.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic