Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding char and int

Tags:

java

char

int

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?

like image 340
Bitmap Avatar asked Apr 27 '12 22:04

Bitmap


People also ask

Can we add char and int?

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.

How do I add a char to an int?

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.

What happens if we add char and int in Java?

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.

Can we add char and int in Python?

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.


1 Answers

You're getting that because it's adding the ASCII value of the char. You must convert it to an int first.

like image 79
Aidanc Avatar answered Oct 20 '22 09:10

Aidanc