javastringasciicharat

How does the charAt() method work with taking numbers from strings and putting them into new strings in Java?


public String getIDdigits()
    {
        String idDigits = IDnum.charAt(0) + IDnum.charAt(IDnum.length() - 1) + "";
        return idDigits;
    }

In this simple method, where IDnum is a 13 digit string consisting of numbers and is a class variable, the given output is never what I expect. For an ID number such as 1234567891234, I would expect to see 14 in the output, but The output is always a three-digit number such as 101. No matter what ID number I use, it always is a 3 digit number starting with 10. I thought the use of empty quotation marks would avoid the issue of taking the Ascii values, but I seem to still be going wrong. Please can someone explain how charAt() works in this sense?


Solution

  • You are taking a char type from a String and then using the + operator, which in this case behaves by adding the ASCII numerical values together.

    For example, taking the char '1', and then the char '4' in your code

    IDnum.charAt(0) + IDnum.charAt(IDnum.length() - 1)
    

    The compiler is interpreting this as its ASCII decimal equivalents and adding those

    49 + 52 = 101
    

    Thats where your 3 digit number comes from.

    Eradicate this with converting them back to string before concatenating them...

    String.valueOf(<char>);
    

    or

    "" + IDnum.charAt(0) + IDnum.charAt(IDnum.length() - 1)