I read that although type byte occupies 8 bits of memory, and type char occupies 16 bits of memory, the conversion from byte to char is considered narrowing because byte is signed, while char is unsigned. I think this means that when we convert a type byte with a negative value to char, we lose the negative and so that is our loss of information and so the conversion is narrowing.
I am trying to test this in a Java program.
public class Test
public static void main (String args)
byte num = -1;
char test = (char)num;
That's not how signs or
System.out.printlnwill show you the UTF-8 character (which is the same as ascii for the first 8 bits of values) for a
System.out.println((char)71);will print "G". So when you expect to see "1" to be printed, what you're saying is that you expect
(char)-1 == 41. If you want the numeric value, you should cast it to
System.out.printlnwill substitute a question mark for unprintable characters.
charfirst is converted to an
int. The doc (linked by Sotirios Delimanolis) says;
First, the byte is converted to an int via widening primitive conversion (§5.1.2), and then the resulting int is converted to a char by narrowing primitive conversion (§5.1.3).
A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits, where n is the number of bits used to represent type T