aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes primitive assignment problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "primitive assignment problem" Watch "primitive assignment problem" New topic
Author

primitive assignment problem

Sugantha Jeevankumar
Ranch Hand

Joined: Jun 06, 2007
Posts: 93
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...


SCJP 5.0
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18896
    
  40

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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Sugantha Jeevankumar
Ranch Hand

Joined: Jun 06, 2007
Posts: 93
Thanks Henry...That was helpful
Sunny Jain
Ranch Hand

Joined: Jul 23, 2007
Posts: 433

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!!


Thanks and Regards,
SCJP 1.5 (90%), SCWCD 1.5 (85%), The Jovial Java, java.util.concurrent tutorial
Dean Jones
Ranch Hand

Joined: Dec 29, 2007
Posts: 129


The above is possible only after applying explicit cast,as in the code below.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: primitive assignment problem