0

I have question about my code in java. I have variable with type data char, with 2 plus '+',

why the result of the code is integer?

public static void main(String args[]) {// kumpulan dari kata kata
        char exampleChar1;
        exampleChar1 = 'A';
        exampleChar1++;
        System.out.println("result of exampleChar1 is : " + + exampleChar1); // result is : result of exampleChar1 is : 66
    }

1 Answers1

1

This is because char can be seen as a type of integer.

The anatomy of your code is: String Operator Cast Char

  1. [String] "result of exampleChar1 is : "
  2. [Operator] +
  3. [Cast] + (this let the compiler thinks you like to calculate 0 + exampleChar1 and therefore casts it to an integer type)
  4. [Char] exampleChar1

Just remove the second + and it should be fine.

System.out.println("result of exampleChar1 is : " + exampleChar1);

If this does not work, force a cast to char:

System.out.println("result of exampleChar1 is : " + (char) exampleChar1);
Alex
  • 1,857
  • 3
  • 36
  • 51