-2
    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?

  • 4
    When you perform arithmetic on a `char`, you transform it to an `int`. The character `'1'` becomes the int 49. – khelwood May 07 '21 at 15:11
  • To add to khelwood, `s.charAt(i)-1` vs `s.charAt(i-1)`. However, I'd guess this will just throw an `IndexOutOfBoundsException` during your first loop. The second line would end up being `s.charAt(-1)` basically. – tnw May 07 '21 at 15:14
  • Related (not the same): [In Java, is the result of the addition of two chars an int or a char?](https://stackoverflow.com/questions/8688668/in-java-is-the-result-of-the-addition-of-two-chars-an-int-or-a-char) – Ole V.V. May 07 '21 at 15:14

3 Answers3

2
s.charAt(i)-1

This line gets the character at index i and 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, the charAt(i) call returns the char that represents 1, and has a value of 49, and then you decrease it by 1, resulting in 48.

You need to convert the character value to an Int before decreasing it. Try:

Character.getNumericValue(s.charAt(i)) - 1
Mateus Bandeira
  • 417
  • 2
  • 5
0

Java does not generally do math on characters. So as soon as you subtract 1 from a char, Java first converts it to int, then subtracts 1 from that int. As the other answer explains, '1' is converted to 49, so you get 48 after the subtraction.

If you wanted the char before '1', just convert back to char before printing:

    String s = "1234";
    for (int i = 0; i < s.length(); i++) {
        System.out.println(s.charAt(i));
        System.out.println((char) (s.charAt(i) - 1));
    }

Output:

1
0
2
1
3
2
4
3

Then it works on letters and punctuation too:

    String s = "Wtf?";
W
V
t
s
f
e
?
>
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
0

I think the problem you are having is that you are getting the character value. You should try converting the string/char to an integer before doing any math to it.

MalcB
  • 51
  • 4