• 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:
  • Tim Cooke
  • Campbell Ritchie
  • Ron McLeod
  • Junilu Lacar
  • Liutauras Vilda
Sheriffs:
  • Paul Clapham
  • Jeanne Boyarsky
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
Bartenders:
  • Jesse Duncan
  • Frits Walraven
  • Mikalai Zaikin

primitive assignment problem

 
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This is a question from javablackbelt.com

Select the valid primitive assignments of the following.


a) int i = 10;
char c = i;

b) float f;
long l = 100L;
f = l;

c) short s = 20;
char c = s;

d) byte b = 20;
char c = b;

I am confused about this one as I thought the answers should be c and d.but its given to be b...please help...Thanks in advance...
 
author
Posts: 23923
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
C and D are incorrect because a short and a byte can both be assigned negative values. Since a char is unsigned, the compiler will complain.

B is correct because the range of a float covers the complete range of the long. Now, you can argue that the float has less precision than a long (especially since it is only 32 bit versus 64 bit for long) -- however, Java doesn't check for loss of precision for implicit casts.

Henry
 
Sugantha Jeevankumar
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Henry...That was helpful
 
Ranch Hand
Posts: 433
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

This is just for your knowledge that if you try the following code :


Compiler will complain as "Possible loss of precision"..but following is valid :


Thanks,
Sunny!!
 
Ranch Hand
Posts: 129
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


The above is possible only after applying explicit cast,as in the code below.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic