0

I once decided to add two chars together, and it gave me a number. Here's the code:

class Main {
  public static void main(String[] args) {
    System.out.println('a'+'b');
  }
}

Output: 195.

I've searched in a lot of places, but I still couldn't figure out why a char + char = int. Can someone explain this to me?

NOTE: THIS IS NOT A DUPLICATE!! The other question is asking the data type of an added char. This question asks why this happens. Those are DIFFERENT QUESTIONS WITH DIFFERENT ANSWERS!

ublec
  • 172
  • 2
  • 15
  • 1
    Here's a decent read on the subject: http://www.vias.org/javacourse/chap07_09.html – Tim Hunter Mar 01 '21 at 20:13
  • 1
    You can check this answer here https://stackoverflow.com/a/8688708/9462470 – b_hunter Mar 01 '21 at 20:15
  • 1
    A simplified way to think about is that `char` variables contain a number value which represents it's position in the ASCII table. Arithmetic operations using `char` have various behaviors depending on how it's used because a `char` contains a number value but represents an character so the system will perform automatic conversions depending on the context of its use. – Tim Hunter Mar 01 '21 at 20:26

3 Answers3

1

You're adding their ASCII values:

'a'+'b' = 97+98 = 195
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
1

5.1. Kinds of Conversion

This code implicitly casts them to String:

System.out.println("" + 'a' + 'b'); //ab

And this code casts to double:

System.out.println(.8 + 'a' + 'b'); //195.8
1

If you want to concatanate, try this :

System.out.println("a"+"b");