int a = 'a'; int b = ('a' + 'b'); 

int declared as a char data type, what do these lines mean?

    2 answers 2

    See it. Your variables are declared as int , but the value is assigned to them using char constants.

    In Java, unlike C ++, char is a 16-bit numeric unsigned type * (as opposed to an 8-bit signed byte ).

    When chars are added, however, integer promotion occurs: char converted to a 32-bit int type, and added together. In this case, obviously, there will be no overflow.

    The result of the addition is also int , it is assigned to the variable b .


    * although its constants ( literals ) are specified by characters like '\u1f2d' , not by numbers

    • "16-bit non-numeric type" - did you mean "unsigned"? Because according to JLS he is quite an integer. - Roman
    • @Roman: According to §4.2.1, char values ​​are the characters '\u0000' .. '\uffff' . It seems to me that this means that in fact the type is non-numeric, the values ​​are not numbers. Although right there beside "that is, from 0 to 65535". So I'm not sure how to interpret this correctly. - VladD
    • Slightly above (4.2) it says: "The integral types are long, our values ​​<...> Those. Values ​​like all the same numbers corresponding to character codes. - Roman
    • @Roman: Yeah, I see. I am still confused that char literals are not written as numbers, but as something-in-single-quotes. Well hmm, correct the answer. - VladD

    In fact, char is an integer type, byte sometimes unsigned. It can be implicitly cast into an int (by character code) and folded. The code is not very beautiful and confuses those who came from C ++.

    UPD. Thanks for the clarification, was not quite right, see the answer VladD.

    • In which case will the overflow? - zed
    • @zed for example E to fold. Or what is the last character in the alphabet? - pavel
    • Immediately there is a cast to int . - zed
    • @zed if I correct something wrong, I'm used to C ++. The result of adding char + char is char and to int later. Those. (int)('a'+'b') but not (int)('a') + 'b' - pavel
    • The last "character" in the alphabet is \uFFFF and even with such an overflow value there will be no. - zed