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?
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.
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.
We can convert a char to a string object in java by using the Character. toString() method.
A char represents a character in Java (*). It is 2 bytes large (or 16 bits).
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 isfinal
and initialized with a compile-time constant expression (§15.28), is called a constant variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With