简体   繁体   中英

Java Implicit conversion char to int?

I was given an interview question to output the most frequent occurrence of a character.

Given this string "aaxxaabbaa". The character 'a' is the most frequent.

The following code was something that I found searching on the internet. Note: I implemented it with 2 loops which is in-efficient (different topic)

public static char findMostUsedChar(String str){
    char maxchar = ' ';
    int maxcnt = 0;
    // if you are confident that your input will be only ascii, then this array can be size 128.
    // Create a character counter
    **int[] charcnt = new int[Character.MAX_VALUE + 1];**
    for(int i = 0; i < str.length()-1; i++){
        char **ch** = str.charAt(i);
        // increment this character's cnt and compare it to our max.
        if (**charcnt[ch]**++ >= maxcnt) {
            maxcnt = charcnt[ch];
            maxchar = ch;
        }
    }
    return maxchar;
}

They declared an int array, found the character at a specific index (ie 'a') then used as an index. After tracing the code out on the debugger in eclipse, I still don't understand how using a character to represent an int index works without explicitly casting it or using charVal.getNumericValue()?? Even most of the SO char to int topics explicitly cast.

Thanks in advance.

Array access expressions undergo implicit unary numeric promotion, which will widen an expression to int .

The index expression undergoes unary numeric promotion (§5.6.1).

The char datatype is widened to int via its Unicode value, eg 'A' -> 65 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM