• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

primitive assignment problem

 
Sugantha Jeevankumar
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • 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...
 
Henry Wong
author
Marshal
Pie
Posts: 21493
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • 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
  • Quote
  • Report post to moderator
Thanks Henry...That was helpful
 
Deepak Chopra
Ranch Hand
Posts: 433
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • 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!!
 
Dean Jones
Ranch Hand
Posts: 129
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


The above is possible only after applying explicit cast,as in the code below.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic