Reputation: 355
If the single quotes are removed in the declaration it is showing 11
class Sample
{
public static void main(String ar[])
{
char v1='5';
char v2='6';
System.out.println(v1 + v2);
}
}
Output: 107
Upvotes: 2
Views: 102
Reputation: 269747
In Java, a char
is a 16-bit, unsigned integral type. When used in arithmetic operations, they are "promoted" to int
operands with the same value.
The Unicode character '5'
has a value of 53, and '6'
has a value of 54. Add them together, and you have 107.
Upvotes: 5
Reputation: 123510
You can get the numeric equivalent of a char
using Character.getNumericValue(char)
:
class Sample
{
public static void main(String ar[])
{
char v1='5';
char v2='6';
int i1 = Character.getNumericValue(v1);
int i2 = Character.getNumericValue(v2);
System.out.println(i1 + i2);
}
}
The function maps chars like '5'
to numbers like 5
.
Fun fact: it also works with other numbering systems like '๕'
, the Thai number 5.
Upvotes: 2