Arefe Arefe - 1 year ago 88
Java Question

Check whether two String's are anagram

I wrote a method for checking whether two Strings are anagram or not. The method is returning true even if the words are not anagram. I don't see any bug in the code, any ideas how can I improve ? The method is as following,

public static boolean checkAnagram( String one, String two){

if ( one.length() != two.length() )
return false;

char[] letters = new char[128];

for ( char c: one.toCharArray()){


for( int j =0; j < two.length(); j++){

int c = (int) two.charAt(j);

if( --letters[c] < 0) return false;


return true;

Answer Source

letters is a char array, so letters[i] can never be negative (the range of char is 0 to 2^16-1). If you try to decrement it below 0, it will underflow to Character.MAX_VALUE. Change it to an int[].

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download