File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

assignement final local variable doubt

 
horri khaled
Ranch Hand
Posts: 36
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
I find this code in javaBeat test



this code cannot compile in (2) because we cannot assign byte variable to a char variable
BUT if i make the (1) like this :


the code work fine, Why?

so if any one can explain that and have more details about this confused code it's be very appreciated.

Khaled
 
Ivan Ivanic
Ranch Hand
Posts: 100
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java Language Specification:
5.1.4 Widening and Narrowing Primitive Conversions
The following conversion combines both widening and narrowing primitive convesions:

* byte to char

First, the byte is converted to an int via widening primitive conversion, and then the resulting int is converted to a char by narrowing primitive conversion.


when you convert byte to char, byte is first converted to int. so compiler knows that there is gonna be some narrowing conversion from int to char. and you can not implicitly convert int to char, except if int is final and falls into range of char. which is your case.
 
horri khaled
Ranch Hand
Posts: 36
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ivan
thanks for the reply
I think that i find the solution in the Mughal book chapter 3:

implicit narrowing primitive conversions on assignment can occur in cases where all of the following conditions are fulfilled:

*the source is a constant expression of either byte, short, char, or int type

*the destination type is either byte, short, or char type

*the value of the source is determined to be in the range of the destination type at compile time

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic