To my understanding a char is a single character, that is a letter, a digit, a punctuation mark, a tab, a space or something similar. And therefore when I do:
char c = '1';
System.out.println(c);
The output 1 was exactly what I expected. So why is it that when I do this:
int a = 1;
char c = '1';
int ans = a + c;
System.out.println(ans);
I end up with the output 50?
Yes, we can store 'char' values in an integer array. But. In that case, the ASCII form of that 'char' value will be assigned to one of the elements of the array.
In Java, char and int are compatible types so just add them with + operator. char c = 'c'; int x = 10; c + x results in an integer, so you need an explicit casting to assign it to your character varaible back.
If we direct assign char variable to int, it will return the ASCII value of a given character. If the char variable contains an int value, we can get the int value by calling Character. getNumericValue(char) method. Alternatively, we can use String.
To increment a character in a Python, we have to convert it into an integer and add 1 to it and then cast the resultant integer to char. We can achieve this using the builtin methods ord and chr.
You're getting that because it's adding the ASCII value of the char. You must convert it to an int first.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With