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

doubt in char to byte convertsion

 
Shubhada Nandarshi
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If c were not final, then the compiler could not know whether its runtime value will fit into the range of a byte.
 
Shubhada Nandarshi
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
that means we can cast char to byte if we declare char as final?
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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;
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic