Java Char addition makes no sense (to me)

So I have this code here:

char a = '1';
char b = '2';
System.out.println(a+b); \\ Outputs 99

I want to know why, since this code:

char a = '1' + '2';

    System.out.println(a); \\ Outputs c

I want to enhance my primitive mind, please help a kindred spirit.

Upvotes: 0

Views: 57

Answers (2)

blurfus
blurfus

Reputation: 14031

They are being added as their decimal numeric ASCII value.

The portion of the code that does a+b implicitly is adding them as integers. So, if you run the following code:

class Example {
    public static void main(String[] args) {
        char ch = '1';
        char ch2 = '2';
        int num = ch;
        int num2 = ch2;
        System.out.println("ASCII value of char " + ch + " is: " + num);
        System.out.println("ASCII value of char " + ch2 + " is: " + num2);
    }
}

You will see that the output of each char is

ASCII value of char 1 is: 49

ASCII value of char 2 is: 50

So when you do this System.out.println(a+b); they get added as their integer value which turns out to be 99

Upvotes: 0

User8500049
User8500049

Reputation: 422

characters hold an value in real; when you write

char a = 49;
char k = '1'; // both of them holds same character because '1' code in ascii 49

and when you treat two variable in arithmetic operation and if one of them type is(byte, short, or char) these types promote in int so

System.out.println(a+b); // both of them promote int
char c = a + b; // assign c, 99 which represents 'c'

Upvotes: 1

Related Questions