If a Java method's return type is int, can the method return a value of
type byte?
I'm preparing myself for the Java SE 7 Programmer I exam (1Z0-803) by
reading a book called OCA Java SE 7 Programmer I Certification Guide. This
book has a numerous amount of flaws in it despite the author having 12
years of experience with Java programming and despite a technical
proofreader, presumably on a salary.
There is one thing though that makes me insecure. The author says on page
168 that this statement is true:
If the return type of a method is int, the method can return a value of
type byte.
Well I argue differently and need your help. Take this piece of code for
an example:
public static void main(String[] args)
{
// This line won't compile ("possible loss of precision"):
byte line1 = returnByte();
// compiles:
int line2 = returnByte();
// compiles too, we "accept" the risk of precision loss:
byte line3 = (byte) returnByte();
}
public static int returnByte()
{
byte b = 1;
return b;
}
Obviously, the compiler do not complain about a different return type int
in the returnByte() method signature and what we actually do return at the
end of the method implementation: a byte. The byte uses fewer bits (8)
than the int (32) and will be cast to an int without the risk of a
precision loss. But the returned value is and will always be an integer!
Or am I wrong? What would you have answered on the exam?
I'm not totally sure what the actual return type is, since this statement
in the book is said to be true. Is the cast happening at the end of our
method implementation or is the cast happening back in the main method
just before assignment?
In the real world, this question would not matter as long as one
understand the implicit casting and the risk of losing precision. But
since this is just one of those questions that might popup on the exam,
I'd love to know the technically correct answer to the question.
No comments:
Post a Comment