0

I'm going through some Java exercises and happened upon this bit of code that I don't fully grok.

public static boolean permutation(String s, String t) {
        if (s.length() != t.length()) {
            return false;
        }

        int[] letters = new int[128];

        char[] s_array = s.toCharArray();
        for (char c : s_array) {
            letters[c]++;
        }
        // omitted other code
}

When I print out the contents of letters, I see an array of integers. Depending on the strings I pass into the function that array returns variations of 0's and 1's.

I thought that maybe the Array class was converting the char to an int. I added a print statement to help but I see the value of d to be 13 yet I see the 13th element in the array still as 0. That code looks like this:

import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
        String word1 = "dog";
        String word2 = "god";
        permutation(word1, word2);
    }

    public static boolean permutation(String s, String t) {
        if (s.length() != t.length()) {
            return false;
        }

        int[] letters = new int[128];

        char[] s_array = s.toCharArray();
        for (char c : s_array) {
            System.out.println(Character.getNumericValue(c));
            letters[c]++;
        }

        System.out.println(Arrays.toString(letters));
        return true;
    }
}

Output:

13
24
16
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

My question being what does Array[char] syntax translate to?

2 Answers 2

1

Character.getNumericValue returns the character "interpreted" as a numeral. For example the character '5' becomes just 5. This also works for unicode characters representing roman numerals for example, or for hexadecimal digits. (Hence 'd' becomes '13'.)

However, when you use a char in a context where an integral value is expected, it is interpreted using its encoding. For example 'a' has the code 97, so array['a'] accesses the 98th element of array.

That's the reason for the discrepancy of your two outputs. ;)

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

Comments

1

the code is counting letters in the input string s. You create letters as new int[128] so you can cover "normal" ASCII characters. Then letters[c]++ is increasing the counter of char c. char can be used as int in Java, so letters[c] refers to letters[<ASCII index of c>]

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.