This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes doubt in char to byte convertsion Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "doubt in char to byte convertsion" Watch "doubt in char to byte convertsion" New topic
Author

doubt in char to byte convertsion

Shubhada Nandarshi
Ranch Hand

Joined: Jun 10, 2005
Posts: 59
hi friends,
please check out the following code...


class test{
public static void main(String[] args) {
final char c = 5; // 1
byte b2 = c; // 2
System.out.println("b2= "+b2);
}

}

in above code we are converting char to byte. But if we do not write final keyword in line 1 then compiler gives an compile-time error. Why so? what is a role of 'final' keyword in this code?


thank you,
Shubhada


Shubhada
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

If c were not final, then the compiler could not know whether its runtime value will fit into the range of a byte.


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Shubhada Nandarshi
Ranch Hand

Joined: Jun 10, 2005
Posts: 59
that means we can cast char to byte if we declare char as final?
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Originally posted by Shubhada Nandarshi:
that means we can cast char to byte if we declare char as final?

Note that we're talking about an "assignment conversion," which means without an explicit cast.

According to JLS - 5.2 Assignment Conversion, "...if the expression is a constant expression (�15.28) of type byte, short, char or int: A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable..."

The key is the definition of "constant expression." Basically, you can assign a char variable's value to a byte variable without an explicit cast if the char variable's value is final, known at compile time, and within the range of a byte.
Dan Polak
Ranch Hand

Joined: Nov 06, 2006
Posts: 32
Originally posted by marc weber:

The key is the definition of "constant expression." Basically, you can assign a char variable's value to a byte variable without an explicit cast if the char variable's value is final, known at compile time, and within the range of a byte.


Right
Like marc said remember about ranges

final int i = 128;
byte ii = i;


<a href="http://www.dantheman.pl" target="_blank" rel="nofollow">http://www.dantheman.pl</a>
 
GeeCON Prague 2014
 
subject: doubt in char to byte convertsion