Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Confused in Assignment

 
Sagar Shroff
Ranch Hand
Posts: 209
Java Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Eclipse IDE Java Oracle
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Java Tomcat Server
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Thank YOU Dennis
And Thank YOU Jacob

 
Tommy Delson
Ranch Hand
Posts: 206
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ... ...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic