aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Question about primitive assignments Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Question about primitive assignments" Watch "Question about primitive assignments" New topic
Author

Question about primitive assignments

Hanna Barenthin
Greenhorn

Joined: Mar 13, 2007
Posts: 14
Hi, this mock-exam question confused me:

Select the valid primitive assignments of the following.

int i = 10;
char c = i;
float f;
long l = 100L;
f = l;
short s = 20;
char c = s;
byte b = 20;
char c = b;
short s1 = 10;
short s2 = 20;
short result = s1*s2;
Hanna Barenthin
Greenhorn

Joined: Mar 13, 2007
Posts: 14
Hi sorry, posted before I was done ;-) The question that got me confused was:

Select the valid primitive assigements:

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;

The correct answer is b). I do not understand why since float has 32 bits and float 64 bits, so how can this be done without a cast? And if it has to do with that 100 is "enough small" to fit in a float reference, why are not the other alternatives also right then since char can hold anything up to 65535?

Happy if someone understands...Thanks
Hanna
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18853
    
  40

Hanna,

Please Quote Your Sources.

Thanks,
Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18853
    
  40

I do not understand why since float has 32 bits and float 64 bits, so how can this be done without a cast?


Hanna,

Keep in mind that a floating point number has range and precision limitations. Believe it or not, a 32 bit float has a larger range than a 64 bit long, hence, the cast is implicit.

Henry
Arad Chear
Ranch Hand

Joined: Jan 05, 2007
Posts: 98
a) invalid because you cannot put int in char loss of precision

b) valid while long can fit into float

c) invalid , char can be assign only int value not byte or short or long
and up to 65535
char c=65536 // error

d) same c

any operation between two numbers ( byte , short , char , int ) the result will be int so
short s1 = 10;
short s2 = 20;
short result = s1*s2 // error possible loss of precision

short result=(short) s1*s2 // fine
Hanna Barenthin
Greenhorn

Joined: Mar 13, 2007
Posts: 14
Thanks! This helped a lot! Sorry for not stating the source, it was the mock exam:

http://www.javablackbelt.com/QuestDefListing.wwa
The exam by Siva Valiveru
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Question about primitive assignments