Char and byte with final access modifier - java

Please take a look below for an example, I cannot understand the relationship between char and byte

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

Give me a compilation Error, because c is a type of char , and b is a type of byte , so in this state, you must cast

but now the twist is here when I run the code below

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

line 2 compiles successfully, it doesn’t need casting at all so my question is why char c behave different when I use the final access modifier with byte

+5
source share
3 answers

Since assigning a variable to final makes the variable a constant variable, which is an expression of constant . 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 into the char variable.

With the variable non constant byte such a guarantee is absent. byte signed, char unsigned .

+11
source

You are working in JLS-5.1.4 Extending and narrowing primitive transforms ,

The following transformation combines both the expansion and the narrowing of primitive transformations:

  • byte to char

First, byte converted to int by extending the primitive transform ( Β§5.1.2 ), and then, as a result, int converted to char by narrowing the primitive transform ( Β§5.1.3 ).

 final byte b = 1; char c = (char) ((int) 2); // <-- 2 is an int literal c = (char) ((int) 1); // <-- b is 1 a byte literal 

If you look at the byte codes with javap -v , you will see that the value 1 has already replaced the variable b after compilation.

 public static void main(java.lang.String[]) throws java.lang.Exception; descriptor: ([Ljava/lang/String;)V flags: ACC_PUBLIC, ACC_STATIC Exceptions: throws java.lang.Exception Code: stack=2, locals=3, args_size=1 0: iconst_1 1: istore_1 // b = 1 2: iconst_2 3: istore_2 // c = 2 4: iconst_1 // integer1. 5: istore_2 // c = 1. 
+2
source

I assume this happens because the java compiler replaces final variable references with its values ​​(almost like a preprocessor in C). Since the value 1 is legal for type char , the last line is converted to

 c = 1; 

which compiled successfully.

+1
source

Source: https://habr.com/ru/post/1207315/


All Articles