It's not clear what you are trying to achieve.
Your code can produce results greater than the string length because of characters that appear more than once in your strings. You can get results of up to num1.length() * num2.length().
In case you want to get the number of positions at which you have the same character in both strings, you can to that in just one loop and use the same index for the "charAt" calls on both strings:
for(int i = 0; i < num1.length() && i < num2.length(); i++) {
if(num1.charAt(i) == num2.charAt(i)){
count++;
}
}
In case you want to get the number of unique letters that appear in both strings, run through both strings independently and add the letters to a set. Then intersect both sets. The number of elements in that intersection set is your result:
Set<Character> characters1 = new TreeSet<Character>();
for(int i = 0; i < num1.length(); i++) {
characters1.add(num1.charAt(i));
}
Set<Character> characters2 = new TreeSet<Character>();
for(int i = 0; i < num2.length(); i++) {
characters2.add(num2.charAt(i));
}
characters1.retainAll(characters2);
return characters1.size();