Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array access with char index in Java

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?

like image 648
Pepe Avatar asked Feb 11 '26 21:02

Pepe


1 Answers

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


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!