0

In "Cracking the Coding Interview" there is a question that wants you to check if two strings are a permutation of one another. After looking at the code, I am confused about why the author's example implementation indexes an array using "char" value of the first string and then after that gets the char values of the second string but casts it into an int before then accessing the same array. Here is a snippet of the code below. You can see that in the first for loop it uses a char value but in the second for loop it casts the char to an int before accessing.:

    boolean isPermutation(String str1, String str2) {
    if (str1.length() != str2.length()) {
        return false;
    }

    int[] charCount = new int[128];

    char[] s_array = str1.toCharArray();
    for (char c : s_array) {
        charCount[c]++;
    }

    for (int i = 0; i < str2.length(); i++) {
        int c = (int) str2.charAt(i);
        charCount[c]--;
        if (charCount[c] < 0) {
            return false;
        }
    }
    return true;
}

1 Answer 1

4

Indexing into an array with a char works almost exactly the same as indexing into it with an int. From the JLS:

Arrays must be indexed by int values; short, byte, or char values may also be used as index values because they are subjected to unary numeric promotion (§5.6.1) and become int values.

So when you index into an array using a char, the char is first promoted to its corresponding int value, and that is used to index into the array. The end result, from a user perspective, is that using a char behaves functionally identically to using an int.

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

3 Comments

Is there a reason why the author chose to do it both ways or was it just to show the reader you can do it either way?
I can't think of a reason why they would have chosen to do it differently. The same conversion to int will happen in both cases. My guess is that, like you say, it's just to show different ways of doing it.
Hmm, that was my first initial thought. I was thrown off because I thought there was some edge case being covered by this explicit conversion to int from a type char in the second for loop.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.