wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes assignement final local variable doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "assignement final local variable doubt" Watch "assignement final local variable doubt" New topic
Author

assignement final local variable doubt

horri khaled
Ranch Hand

Joined: Mar 24, 2008
Posts: 36
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


SCJP 5
Ivan Ivanic
Ranch Hand

Joined: Oct 31, 2007
Posts: 100
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.


<a href="http://faq.javaranch.com/java/UseRealWords" target="_blank" rel="nofollow">Use Real Words</a> <a href="http://faq.javaranch.com/java/UseCodeTags" target="_blank" rel="nofollow">!!!Use Code Tags!!!</a> <a href="http://faq.javaranch.com/java/SayThanks" target="_blank" rel="nofollow">Say Thanks</a><br />scjp6
horri khaled
Ranch Hand

Joined: Mar 24, 2008
Posts: 36
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

 
It is sorta covered in the JavaRanch Style Guide.
 
subject: assignement final local variable doubt