Search code examples
javaarraysstringserversocket

Converting String to Char array in JAVA


I am using the toCharArray method to convert a string to an array of type char but every time i try to print the array, it is printing numbers instead of the characters stored in the string. When i print the string the characters are printed just fine.

char[] nArray = capitalizedSentence.toCharArray();

        for (int i = 0; i < nArray.length; i++)
        {
            System.out.println(nArray[i] + '\n');
        }

EXAMPLE: If my capitalizedSentence string has the value "Saad", when i convert it to a character array and print it, it prints the following:

93
75
75
78

can someone please help me so that it prints the individual characters stored in the capitalizedSentence string?


Solution

  • nArray[i] is a char; so is the '\n' constant. Character is an unsigned integral type, so characters are added together in the same way as all integers - numerically. When an addition happens, you end up with an int, not a char, so calling println on it produces a numeric result.

    Removing + '\n' will fix the problem. You would get a newline character from println, so all characters would appear on a new line.

    Demo.