Search code examples
javastringcastingadditioncharat

Strange behaviour at String addition on Java


I have noticed something strange when adding two chars in a string when casting them to an integer.
For the following code I have s1 = "+1" and s2 = "+2" as input:

String s1 = scanner.next();
String s2 = scanner.next();

System.out.println(s1.charAt(1));
System.out.println((int)s1.charAt(1));

The output is:
1
49

Then I tried also the following:

Input:
+1
+2

Code:

System.out.println(s1);
System.out.println(s2);
System.out.println((int)(s1.charAt(1)) + (int)(s2.charAt(1)));

Output:
+1
+2
99

Why is it like this? Why is the output not "3" and what can I do to get it to three?


Solution

  • This is because when you're typecasting a character to an integer it gives you the ascii value of that character instead of converting it.

    ascii value of 1 = 49 and 2 = 50 so, 49 + 50 = 99.

    Instead of typecasting you should use parsing.

    Integer.parseInt(s1.charAt(1)); will give you 1 instead of 49.

    Try it out.