aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes expressions Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "expressions" Watch "expressions" New topic
Author

expressions

d jones
Ranch Hand

Joined: Mar 13, 2006
Posts: 76
Hi,

In the K&B book for SCJP 1.4 on page 148 in Chapter 3 it states that "the result of an expression involving anything int sized or smaller is an int".

However,
byte a = 1 + 1;
This compiles and runs fine.

But,
int q =1;
int z = 1;
byte a = q + z;
This does not compile.

Could somebody please explain the difference between the above addition statements. I would've thought that they were the same since any numeric literal is always an int.

Am I interpreting the K&B book incorrectly?

Many Thanks
Surendra Kumar
Ranch Hand

Joined: Jul 04, 2006
Posts: 235
In the first one, compiler knows that you're assging 2 to byte, which is fine.

In the second expression, the evaluation happens at runtime and the compiler assumes that the evaluation is at least an integer which can not be assigned to byte.
d jones
Ranch Hand

Joined: Mar 13, 2006
Posts: 76
Thanks Surendra,

Each time I think I understand a topic I come across a question like this which just leaves me completely confused.

Your point wasn't made clearly in the K&B book. Is that because it is not relevant for the SCJP 1.4 exam???

Thanks
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

This situation could be on the exam.

In both cases, the result of the expression on the right side of the equals sign is an int. The difference is in trying to assign that int result to the byte variable on the left side of the equals sign.

In the case of byte a = 1 + 1; int literals are being added, and so the result is known at compile time. In particular, the compiler "knows" that the int result is within the range of a byte, and so it's okay.

But in the case of byte a = q + z; int variables are being added, and so the result cannot be known at compile time. Therefore, the compiler has no way of "knowing" whether the result will be within the range of a byte. (Actually, "variables" would be okay, if they are final with their values known at compile time. See this thread.)
[ August 29, 2006: Message edited by: marc weber ]

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: expressions