This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
sagar shroff wrote:When we assign something like this
The Compiler will give error because addition of two a+b will result into integer... It needs to be cast like this c=(int)a+b;
That's fine i understood this.But when i tried something like this
final byte a=1;
final byte b=2;
It compiled without the cast.
CAN SOMEONE EXPLAIN ME THIS ???
In the first case, the compiler can not be certain that the addition will result in a value small enough to be held in a byte. So the cast is required. In the second case, a and b are declared final. The compiler knows their values, and thus knows that a byte can hold the sum. So no cast is required.
Sagar...Dennis's explanation is perfect...This line of code is called a compile-time-constant. And as Dennis said the keyword final makes the compiler aware of its values and has a guarantee of the expressions result. The case is NOT the same for objects.
In Your Pursuit Towards Certification, NEVER Give Up.
Try the two examples below. They are based on the ideas already
discussed. The first compiles without error because the compiler
knows that the result is 127, the maximum allowed value for b3. But in the second example, the result is 128 which is too big for b6. So the
compiler show an error.