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.
Big Moose Saloon
 Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies Register / Login Win a copy of Refactoring for Software Design Smells: Managing Technical Debt this week in the OO, Patterns, UML and Refactoring forum!

# Confused in Assignment

Sagar Shroff
Ranch Hand

Joined: Jun 07, 2011
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 ???

OCJP-90%,OCPWCD-95%
dennis deems
Ranch Hand

Joined: Mar 12, 2011
Posts: 808
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

Joined: Aug 31, 2010
Posts: 394

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

OCPJP 6.
In Your Pursuit Towards Certification, NEVER Give Up.
Sagar Shroff
Ranch Hand

Joined: Jun 07, 2011
Posts: 209

Thank YOU Dennis
And Thank YOU Jacob

Tommy Delson
Ranch Hand

Joined: Apr 13, 2011
Posts: 206
Need to know more about "compile time constant" ?

Check this out:

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

OCPJP6-05-11
"Your life is in your hands, to make of it what you choose."
Jim Hoglund
Ranch Hand

Joined: Jan 09, 2008
Posts: 525
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 ... ...

BEE MBA PMP SCJP-6

Have you checked out Aspose?

subject: Confused in Assignment