This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
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

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "expressions" Watch "expressions" New topic


d jones
Ranch Hand

Joined: Mar 13, 2006
Posts: 76

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".

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

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: 236
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???

marc weber

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
I agree. Here's the link:
subject: expressions
It's not a secret anymore!