aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Cast conversion 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 "Cast conversion" Watch "Cast conversion" New topic
Author

Cast conversion

Santosh Jaiswal
Greenhorn

Joined: Oct 04, 2000
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;
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

Joined: Oct 24, 2000
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"

Sean <br />SCJP2, SCJP2p1.4, SCWCD
Kathy Rogers
Ranch Hand

Joined: Aug 04, 2000
Posts: 103
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

Joined: Oct 04, 2000
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).]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Cast conversion