Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# Confused in Assignment

Sagar Shroff
Ranch Hand
Posts: 209
When we assign something like this

byte a=1;
byte b=2;
byte c=a+b;
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;
byte c=a+b;

It compiled without the cast.
CAN SOMEONE EXPLAIN ME THIS ???

dennis deems
Ranch Hand
Posts: 808
• 2
sagar shroff wrote:When we assign something like this

byte a=1;
byte b=2;
byte c=a+b;
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;
byte c=a+b;

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.

Ikpefua Jacob-Obinyan
Ranch Hand
Posts: 394
• 1
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.

Regards

Ikpefua

Sagar Shroff
Ranch Hand
Posts: 209
• 1

Thank YOU Dennis
And Thank YOU Jacob

Tommy Delson
Ranch Hand
Posts: 206
• 1
Need to know more about "compile time constant" ?

Check this out:

http://www.coderanch.com/t/454384/java/java/compile-time-constant

Jim Hoglund
Ranch Hand
Posts: 525
• 1
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.

Jim ... ...