Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trying to check if a string is Palindrome but concatenation is NOT working

I have below code where the uncommented line in loop is not working as the commented line to check if it is palindrome.

String s = "madam";
String reversed = "";
for (int i = s.length() - 1; i >= 0 ; i--) {
            reversed.concat(Character.toString(s.charAt(i)));
//          reversed += s.charAt(i);
}
return s.equals(reversed)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

As @Mirek Pluta hinted in the comments:

You should reassign reversed to the result of reversed.concat(...)

for (int i = s.length() - 1; i >= 0 ; i--) {
    reversed = reversed.concat(Character.toString(s.charAt(i)));
}

Note that reversed += s.charAt(i); is effectively the same as reversed = reversed + s.charAt(i);.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading