Having passed my
SCJP 1.4 over a year ago I have forgotten lots of stuff. So taking the first example I look up the
API for Byte. I see it has two constructors, one taking a
byte the other a
String. The first two variables b1 and b2 are candidates for the constructor which takes a
byte, and the third variable b3 is a candidate for the constructor which takes a
String. Now 1 and '2' are
int literals and I know that these are
not going to compile without a cast to
byte. The API for the constructor which takes a
String says that the method to parse the string is the same as the
parseByte method, which requires decimal digits with an optional minus sign, and a numerical value that fits into a
byte. 3 is in the range [-128, 127] so we are OK, that will compile
and parse at runtime.
The last part is the assignment. So check the API again and I see that byteValue() returns a
byte. The result of the additions will be an
int which needs a cast back to a
byte for the assignment to work.
So I think we have 3 lines giving a compile error.
My next step is to put the code into my
testing IDE (BlueJ) and try to compile it. Yup three errors. I correct those errors by inserting the required casts and run the program. Yes, it runs and produces 54. 54? Ah yes the character literal '2' is the reason, it has value 50 = 0x32 (16) = 062 (8). A quick look at
this ASCII table verifies this.
That's my method for Dan Chisholm's problems. I (re)learnt and reinforced this stuff in my tired old brain. There's no easier way. If in doubt, use the compiler to sort you out. Roll on SCJP 1.5

[ September 21, 2004: Message edited by: Barry Gaunt ]