Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Type Conversion

 
Salima Lalani
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
This eg. is from khalid Mughal.
int i = -20;
final int j = 20;
byte b1 = j;//final value of j in range.No cast required
byte b2 = i; //Compiler Error. Cast required.
If i declare int j without 'final' keyword then compiler will ask for casting otherwise not.
Could somebody help me to understand this.
Thanks in advance,
Salima
 
Anthony Villanueva
Ranch Hand
Posts: 1055
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A narrowing primitive conversion (like int to byte) may be used if the value of the expression is known at compile time, and is representable in the type of the variable. Declaring it as final effectively makes the value known at compile-time. I think there are also a lot of threads on this topic.
 
Larry Lecomte
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From JLS 5.2:
In addition, a narrowing primitive conversion may be used if all of the following conditions are satisfied:
* The expression is a constant expression of type byte, short, char or int.
* The type of the variable is byte, short, or char.
* The value of the expression (which is known at compile time, because it is a constant expression) is representable in the type of the variable.
 
Salima Lalani
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks,
Where can i find more on this topic?
Reply
Salima
 
suresh kamsa
Ranch Hand
Posts: 149
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic