3

While seeing the explanation for a Java programming exercise online, I came upon the following piece of code:

int[] count = new int[128];
int length = 0;
for(char c: s.toCharArray()){
    if(++count[c] == 2){
        length += 2;
        count[c] = 0;
    }
}

I understand what the code does but I don't know how it can access an array element using a char index (i.e.count[c], where c is a char). I thought indexes could only be integers?

3
  • 2
    every char is an integer (or can implicitly and silently converted to one without any loss of data), but not every integer is a char. Commented Sep 3, 2019 at 14:44
  • int i = c; if (++count[i] == 2) is what is happening, where one can have an IndexOutOfBoundsException for non-ASCII (§ é € ½ ©) Commented Sep 3, 2019 at 15:10
  • To the extent it is useful, new int[Character.MAX_VALUE+1] would cover all UTF-16 code units. It probably wouldn't be useful for Unicode codepoints that UTF-16 encodes in two code units 😉, nor for grapheme clusters (aka "user-percieved characters"). But is seems you expect only the C0 Controls and Basic Latin characters. Commented Sep 3, 2019 at 16:32

3 Answers 3

4

The char is implicitly cast to an int. The index is still an int.

Sign up to request clarification or add additional context in comments.

Comments

1

A char (16 bit) is an int (32 bit), not vice versa. This is an implicit casting, char to unsigned int in particular. In this case, the index will probabily be the ASCII code representing this char (for ASCII characters).

2 Comments

Thanks!! Does this also happen with other types (e.g. strings) ?
No, basically because String is not a primitive type. A string can contains more then one char and there is not implicit conversion. Maybe you can put an integer in a String and the make an explicit conversion to int, but is not a very good idea...
0

So Basically Each Character is defined by Ascii value. So when you try to use char as int. It will use it as defined Ascii value.

That's why its working.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.