0

I've got a strange issue with int to char conversion. Here's my code :

    char a=100;
    System.out.println(a);
    System.out.println(a+1);
    System.out.println();

    System.out.println((char)a+1);
    System.out.println((char)101);
    System.out.println( (char)a+1==(char)101 );

It gave me this output :

d
101

101
e
true

which is definitly strange : two differents output seems to be the same when compared ! Why is it so ? And how to make a+1 beeing seen as a char ?

Thank you for your answer and sorry if there's some english mistakes, it's not my mothertongue.

Racater
  • 1
  • 2

2 Answers2

4

In this case

System.out.println((char)a+1);

you are only converting the a to a char (which it is already). The addition makes the whole expression an int, so the overloaded PrintWriter#println(int) gets executed. For it to be seen as a char, do

System.out.println((char) (a+1));

In the JLS

The binary + operator performs addition when applied to two operands of numeric type, producing the sum of the operands.

The type of an additive expression on numeric operands is the promoted type of its operands.

and about promotion

Widening primitive conversion (ยง5.1.2) is applied to convert either or both operands as specified by the following rules:

  • If either operand is of type double, the other is converted to double.

  • Otherwise, if either operand is of type float, the other is converted to float.

  • Otherwise, if either operand is of type long, the other is converted to long.

  • Otherwise, both operands are converted to type int.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
1

When you use this way:

(char)a + 1

It firstly converts a => char, after this you add 1 of type integer.

And result of calculation is upcasted to integer type.

You can omit this tricky place if you will cast all expression together:

(char)(a + 1)

catch23
  • 17,519
  • 42
  • 144
  • 217