-6

Here is the code, it works, it converts 66 into the ASCII equivalent of B.

int ascii = 66;
char character = (char) ascii;

What I don't understand is, how does it work? If this was an exam paper, what would you write?

The question would be, describe how the program converts it into a "B". Is char a function?

vidit
  • 6,293
  • 3
  • 32
  • 50
user2421111
  • 109
  • 2
  • 3
  • 8
  • `char` is a type and there is nothing to do to display 66 as 'B'. In fact to display `66` requires conversion to two characters 54 and 54 which print as `6` and `6`. – Peter Lawrey Jun 02 '13 at 08:53

1 Answers1

0

"char" => "int" is called Widening Primitive Conversion and "int => char" is called Narrowing Primitive Conversion

In Java, a char is just a 16-bit integer. When casting ints (which are 32-bit integers) to chars, you are keeping the 16 least significant bits of the int, and discarding the upper 16 bits. This is called a narrowing conversion. Java characters are represented as members of the Unicode character set. The Unicode value of 'B' is 66.

int ascii = 66;

The integer value 66 is assigned to ascii.

char character = (char) ascii;

character stores the first 16 bits of the integer ascii. Storing 66 doesnt exceed 16 bits so the char variable gets it right

Tejas Patil
  • 6,149
  • 1
  • 23
  • 38