Search code examples
javaeclipsedata-structuresintegerchar

Java: difference of chars


I'm experimenting with characters in Java

snippet 1

char c='b'-'a';

snippet 2

char c='b'-'c'; // error: java: incompatible types: possible lossy conversion from int to char

Why doesn't the operation work as opposed to snippet 1, but works when I cast it to char


Solution

  • Java char is an unsigned(non-negative) 16-bit integral type.

    Therefore snippet 2 is prone not to work which essentially is performing: 98-99 ('c'-'b')

    And for snippet 1 it is indeed expected to show some unprintable character but Eclipse is weirdly printing A as an output

    Output