String s = "1234";
for(int i=0;i<s.length();i++)
{
System.out.println(s.charAt(i));
System.out.println(s.charAt(i)-1);
}
In the above line of code , for the first iteration, i.e., when i=0, first line should print 1 and second one should print 0 but the second one is printing 48. Why is it so?
This line gets the character at index
iand decreases it by one. The first thing you need to know is that characters have a numeric value as well, and you can do math with them. The ASCII value of the character "1" is 49 (take a look at the table: https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html). So, thecharAt(i)call returns the char that represents1, and has a value of49, and then you decrease it by1, resulting in48.You need to convert the character value to an Int before decreasing it. Try: