0

I came across this code which is using .toCharArray() to create a hashcode of a string which will be later used to store data in a HashMap.

    public static int generateHashCode(String s) {
    int code = 0;
    
    for(char next_character: s.toCharArray()) {
        code += next_character;
    }
    
    return code;
}

What I understand from this code is that it's using an enhanced for loop to traverse through each character of the string(Made array). What I don't understand is that how it's adding those "characters" to an "integer"-code. I changed the code to just print next_character and it printed all the individual characters of the strings.

  • try printing `(int) next_character` - will return the UTF-16 code of that character - and a character is an integral type by [Java Language Specification](https://docs.oracle.com/javase/specs/jls/se16/html/jls-4.html#jls-4.2.1-100-E) - it is printed as a character (not converted to integer representation, as other number) –  Mar 26 '21 at 23:37

1 Answers1

-1

What’s happening here is that the char is being promoted to an int, its value will be equal to the ASCII value.

https://en.m.wikipedia.org/wiki/ASCII

David Brossard
  • 13,584
  • 6
  • 55
  • 88
Kevvvvyp
  • 1,704
  • 2
  • 18
  • 38
  • Oh, that makes sense but how's that happening? Does java automatically understand that the user is trying to add a character to an int and therefore converts the character to its ASCII equivalent number? –  Mar 26 '21 at 22:50
  • https://stackoverflow.com/q/8688668/2023052 – Kevvvvyp Mar 26 '21 at 22:57
  • `ASCII` only if it is not greater than `\u007f` (127) –  Mar 26 '21 at 23:46