Hanna Barenthin
Greenhorn
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
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
Marshal
Posts: 21023
78
Hanna,

Thanks,
Henry

Henry Wong
author
Marshal
Posts: 21023
78
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

Ranch Hand
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
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