Simon Roberts in his book Java @ certification guide mentions with refernce to Unary operators that There are 2 rules that apply depending on the type of the operand 1)If one of the oprtnad is a byte, a short or a char,itis converted to an int using this rule the code given below when compiled should give a type mismatch error as converting an int to a char requires a cast.Surprisingly not only does this code compile but when it is run,The output is - The character is now b Why does this hapen ?
I don't think char is actual converted to a int during any arithmetic operation. According to Peter van der Linden in Just Java 2 page 96, char is an integer-based type with all arithmetic operators available. The code above will first produce an 'a' since x is assigned 97 (the decimal value of 'a' in the ASCII table). The char casting for x is required since char is a unsigned 16-bit type and int is a signed 32-bit type so the result of the assignment will be smaller. If y is then cast to int it will print 97. Any arithmetic done to y is performed as if y were an integer(char is a integer-base type). Hope this is right, makes sense and helps.