Search code examples
javacharbyteprimitivescjp

char and byte with final access modifier - java


Please take a look at below example i cant understand the relation between char and byte

byte b = 1;
char c = 2;

c = b; // line 1

Give me compilation Error because c is type of char and b is type of byte so casting is must in such condition

but now the tweest here is when i run below code

final byte b = 1;
char c = 2;

c = b; // line 2

line 2 compile successfully it doesn't need any casting at all so my question is why char c behave different when i use final access modifier with byte


Solution

  • Because qualifying it with final makes the variable a constant variable, which is a constant expression. So

    final byte b = 1;
    char c = 2;
    
    c = b; // line 2
    

    actually becomes

    final byte b = 1;
    char c = 2;
    
    c = 1;
    

    And the compiler has a guarantee that the value 1 can fit in a char variable.

    With a non constant byte variable, there is no such guarantee. byte is signed, char is unsigned.