String a ="sdfasdfasdf"; String b ="asdfhearhmykky"; for(char i :a.toCharArray() ){ if(b.indexOf(i)!=-1){ System.out.print(i); } }