view raw
Sheikh Rahman Sheikh Rahman - 6 months ago 40
Java Question

Java Given 2 Strings write a method to decide if one is a permutation of the other

That is a question from Cracking the coding interview.Below is my code:

class PalinDrome {

public static Scanner userinput = new Scanner(;
public static void main(String [] args){

//1st input from user
System.out.println("Enter 1st string: ");
String s1=;

// convert 1st string to char Array

char [] charS1= s1.toCharArray();


//2nd input from user
System.out.println("Enter 2nd string: ");
String s2=;

// convert 2nd string to char Array

char [] charS2= s2.toCharArray();


if(s1.length()==s2.length() && s1.toCharArray()==s2.toCharArray()){
System.out.println(" Word 2 is Perm of 1st word");
System.out.println(" Word 2 is not Perm of 1st word");


Question: When I use Tom(1st) and 2nd Mot/moT (tried different variations), I always get Not perm of 1st word. There are answers in the book, I want to know whats wrong with this logic. Thank in advance.


As mentioned in the comment s1.toCharArray()==s2.toCharArray() is wrong because you are not really comparing values in the array just the references of those 2 newly created arrays. You should sort those arrays Arrays.sort And then use Arrays.equals to compare those arrays.