Simon Roberts in his book Java 2 certification guide mentions with reference to Unary operators that There are 2 rules that apply depending on the type of the operand 1)If one of the operand is a byte, a short or a char,it is 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 ?
[This message has been edited by dhruv simaria (edited March 27, 2001).]
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.