JAVA program to check if the string is a palindrome
This JAVA program is to check if the string is a palindrome or not. Palindrome strings are which when written in reverse also produce the same string.
For example, dad is a palindromic string as when written in reverse also produces string dad.
Logic
We keep comparing the first character with the last, the second with second last and so on.If at any instant both characters do not match we for sure know that it is not a palindrome.
Dry Run of the Program
Take input string ‘s’.Let us take s=dad
Convert string to char array ‘str’
flag is initialized to 0 i.e. flag=0
n=str.length; hence n=3
1st iteration for(i=0;i<n;i++) i.e. for(i=0;0<3;i++)
if(str[i]!=str[n-i-1]) i.e. if(str[0]!=str[3-0-1]) i.e. if(str[0]!=str[2]) i.e. if(d!=d) which is false as d=d
2nd iteration for(i=1;i<n;i++) i.e. for(i=1;1<3;i++)
if(str[i]!=str[n-i-1]) i.e. if(str[1]!=str[3-1-1]) i.e. if(str[1]!=str[1]) i.e. if(a!=a) which is false as a=a
3rd iteration for(i=2;2<n;i++) i.e. for(i=2;2<3;i++)
if(str[i]!=str[n-i-1]) i.e. if(str[2]!=str[3-2-1]) i.e. if(str[2]!=str[0]) i.e. if(d!=d) which is false as d=d
For loop ends here as now i(3) is not less than n(3).
if(flag==0) i.e. if(0==0) true
We print that the given string “dad” is a palindrome.
Program
import java.util.*; class stringPalindrome { public static void main(String args[]) { int n,i,flag=0; String s; Scanner sc = new Scanner(System.in); System.out.println("Enter the string"); s=sc.nextLine(); char str[]=s.toCharArray(); n=str.length; for(i=0;i<n;i++) { if(str[i]!=str[n-i-1]) { flag=1; break; } } System.out.println("Is the string a palindrome?\n"); if(flag==0) { System.out.println("YES"); } else { System.out.println("NO"); } } }