Amit Manocha
Amit Manocha

Reputation: 61

Java String Comparison fails

Why does this string comparison fail?

package javaapplication57;

/**
*
* @author amit
*/
public class JavaApplication57 {

    /**
    * @param args the command line arguments
    */
    public static void main(String[] args) {
        String a = "anagram";
        String b = "margana";
        int len = a.length();
        char[] temp = a.toCharArray();
        char[] temp2 = b.toCharArray();
        int len2 = b.length();

        for(int j = 0; j<len-1; j++)
        {    
            for(int i = 0; i<len-1; i++)
            {
                if(temp[i]>temp[i+1])
                {
                    char t = temp[i];
                    temp[i] = temp[i+1];
                    temp[i+1] = t;
                }
            }
        }
        //System.out.println(temp);

        for(int j = 0; j<len2-1; j++)
        {    
            for(int i = 0; i<len2-1; i++)
            {
                if(temp2[i]>temp2[i+1])
                {
                    char t = temp2[i];
                    temp2[i] = temp2[i+1];
                    temp2[i+1] = t;
                }
            }
        }
        //System.out.println(temp2);
        if(temp.equals(temp2))
        {
            System.out.println("yes");
        }
    }

}

Upvotes: 3

Views: 2846

Answers (3)

Daniel Oluwadare
Daniel Oluwadare

Reputation: 35

Assuming you are not using built in methods, you have to first check for a case: The length of both strings have to be equal. No need to use a char array just go through both strings, after checking if lengths are equal.

public static boolean equals(String str, String str2){

      if(str.length() != str2.length()){
         return false;
      }
      for(int i=0; i<str.length(); i++){
         if(str.charAt(i) != str2.charAt(i)){
            return false;
         }
      }
      return true;
   }

Upvotes: 1

Yamen Nassif
Yamen Nassif

Reputation: 2486

just use the .equals method from java

String a = "anagram";
String b = "margana";
if(a.equals(b){
    System.out.pring("equals");
}else{
    System.out.pring("not equals";
}

Upvotes: 2

Eran
Eran

Reputation: 394146

You are not comparing Strings. You are comparing arrays of char. Arrays don't override Object's equals, so equals behaves the same as ==. You can create Strings from the arrays you wish to compare and run equals on the resulting Strings.

if(new String(temp).equals(new String(temp2)))

Upvotes: 6

Related Questions