Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Cast conversion

 
Santosh Jaiswal
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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;
My answer - b,c,e, but answer given is b,e

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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic