I am a beginner in Java programming. I was a making a program to find if the entered word is a pallindrome or not can someone please tell me the logic i should use to make the given program?
Asked
Active
Viewed 167 times
-5
-
2google it!!! :) – Sarthak Mittal Sep 15 '16 at 14:15
-
typing that exact question into google gives you plenty of results – UnholySheep Sep 15 '16 at 14:16
-
Basically a palindrome is a word where the last character is equal to the first character. The second from the front equals the second from the rear and so on... Do you see the pattern? ;-) – DBX12 Sep 15 '16 at 14:17
-
You should really try to find a solution first and come back here when you are stuck and need help. For a simple solution try iterating over your input from both directions simultaneously and compare the characters. – Florian Link Sep 15 '16 at 14:18
-
The easiest way I can think is to reverse the characters in the word and then compare that to the original word. This post explains how to reverse a word in Java: http://stackoverflow.com/questions/7569335/reverse-a-string-in-java#7569370 – Mike Taverne Sep 15 '16 at 14:19
-
Ok got it Thank you friends. – Arpit Sep 15 '16 at 14:19
-
I answered your question below. – Tim Biegeleisen Sep 15 '16 at 14:20
-
@Tim Biegeleisen Thnxx – Arpit Sep 15 '16 at 14:21
-
1boolean isPalindrome = new StringBuilder(input).reverse().toString().equals(input); – Adriaan Koster Sep 15 '16 at 14:24
-
Thnxx to all bye. – Arpit Sep 15 '16 at 14:26
1 Answers
0
boolean isPalindrome(String input) {
for (int i=0; i < input.length() / 2; ++i) {
if (input.charAt(i) != input.charAt(input.length() - i - 1)) {
return false;
}
}
return true;
}
This solution is self explanatory, the only edge case requiring explanation is what happens for words with an odd number of letters. For an input containing an odd number of letters, the middle element will not be touched by the loop, which is OK because it has no effect on whether the input is a palindrome.

Tim Biegeleisen
- 502,043
- 27
- 286
- 360