Win a copy of The Business Blockchain this week in the Cloud forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

expressions

 
d jones
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 236
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic