Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java char to byte casting

Tags:

I have been testing the char casting and I went through this:

public class Test {     public static void main(String a[]) {         final byte b1 = 1;         byte b2 = 1;         char c = 2;          c = b1; // 1- Working fine         c = b2; // 2 -Compilation error     } } 

Can anyone explain why it's working fine in 1 when I added a final to the byte?

like image 418
oueslatibilel Avatar asked May 20 '15 10:05

oueslatibilel


People also ask

How do you turn a character into a byte?

Step 1: Get the character. Step 2: Convert the character into string using ToString() method. Step 3: Convert the string into byte using the GetBytes()[0] Method and store the converted string to the byte. Step 4: Return or perform the operation on the byte.

Why is a Java character 2 bytes?

Java support more than 18 international languages so java take 2 byte for characters, because for 18 international language 1 byte of memory is not sufficient for storing all characters and symbols present in 18 languages.

How do I convert a char to a string in Java?

We can convert a char to a string object in java by using the Character. toString() method.

How many bytes is a char Java?

A char represents a character in Java (*). It is 2 bytes large (or 16 bits).


1 Answers

When the variable is final, the compiler automatically inlines its value which is 1. This value is representable as a char, i.e.:

c = b1; 

is equivalent to

c = 1; 

In fact, according to this section on final variables, b1 is treated as a constant:

A variable of primitive type or type String, that is final and initialized with a compile-time constant expression (§15.28), is called a constant variable.

like image 163
M A Avatar answered Sep 17 '22 13:09

M A