This week's book giveaway is in the Other Languages forum.We're giving away four copies of Functional Reactive Programming and have Stephen Blackheath and Anthony Jones on-line!See this thread for details.
Win a copy of Functional Reactive Programming this week in the Other Languages forum!

# Cast conversion

Santosh Jaiswal
Greenhorn
Posts: 26
Given the variable declarations below:
byte myByte;
int myInt;
long myLong;
char myChar;
float myFloat;
double myDouble;
Which one of the following assignments would need an explicit cast?
a) myInt = myByte;
b) myInt = myLong;
c) myByte = 3;
d) myInt = myChar;
e) myFloat = myDouble;
f) myFloat = 3;
g) myDouble = 3.0;

In Barry Boone's book I found as
int i = 5;
byte b = (byte)i;
Can anyone help me ?

sean cee
Ranch Hand
Posts: 115
Hi,
I agree with you. you can compile the code.
and you will see that if you go:
int i =9;
byte b=8;
i = b; is OK
b = i ; will complain "possible loss of precision"

Kathy Rogers
Ranch Hand
Posts: 104
You're right that the following code won't compile without an explicit cast:
int i = 3;
byte b =i;
But the question assigns a literal value (an actual number) rather than a value held in another variable.

byte b = 3;
It assigns the value 3, which is well within the range of values that a byte can hold (-2^7 to 2^7 -1). So there's no need for a cast.
Hope this helps,
Kathy

Santosh Jaiswal
Greenhorn
Posts: 26
Does it mean that when we assign a int literal (which is within byte range) to byte , we don't need cast.
byte b = 3;
But when we assign a int variable to byte we always need a cast , even if the int var holds a value which is within a range ?
int i=3;
byte b =(byte)i
Is it so b'coz java isn't sure of the value of i at compile time?
Thanks

[This message has been edited by Santosh Jaiswal (edited October 27, 2000).]