In this article, we will see how to implement palindrome program in java.
A palindrome is a word, phrase, number, or other sequence of symbols or elements that reads the same forward or reversed.
For example: 12121 is palindrome as it reads same forward or reversed. madam is also a palindrome .
This is very simple interview question.There are many ways to check if given string is palindrome or not.
Reversing a String and then comparing it with input String:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
packageorg.arpit.java2blog;
import java.util.Scanner;
publicclassStringFullLoopPalindrome{
publicstaticvoidmain(String[]args){
Scanner scanner=newScanner(System.in);
System.out.print("Enter string : ");
Stringstr=scanner.nextLine();
StringreverseStr="";
for(inti=str.length()-1;i>=0;i--){
reverseStr=reverseStr+str.charAt(i);
}
if(str.equals(reverseStr)){
System.out.println("String is palindrome");
}else{
System.out.println("String is not palindrome");
}
}
}
Run above program, you will get following output:
1
2
3
4
5
6
Enter string:12121
Stringispalindrome
Enterastring:Apple
Stringisnotpalindrome
Using half loop,Moving from both end of String simultaneously: