Arefe Arefe - 7 months ago 41
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;


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[].