Java Tutorial For Beginner ~ Checking Palindrome program

in #programming7 years ago


This tutorial presents a program that checks whether a string is a palindrome.

A string is a palindrome if it reads the same forward and backward.

The words “bob,” “kink,” and “noon,” for instance, are all palindromes.

This program is going to prompt the user to enter a string and reports whether the string is a palindrome.

import java.util.Scanner;

public class CheckingPalindrome {
public static void main(String[] args) {
//create scanner object
Scanner input = new Scanner(System.in);
//prompt the user to enter a string
System.out.print("Enter A String of your Choice: ");
String pal=input.nextLine();
//index of the first character in the string
int first =0;
//index of the last character in the string
int last=pal.length()-1;

   boolean isPalindrome=true;
   while (first<last){
       if (pal.charAt(first)!=pal.charAt(last)){
           isPalindrome=false;
           break;
       }
       first++;
       last--;
   }
   if (isPalindrome)
       System.out.println(pal + " is a Palindrome ");
   else
       System.out.println(pal+ " is not a Palindrome");
}

}

Explanations that will help you understand the program.

The program uses two variables, first and last, to denote the position of the two characters at the beginning and the end in a string pal. Initially, first is 0 and last is pal.length() – 1. If the two characters at these positions match, increment low by 1 and decrement high by 1. This process continues until (first >= last) or a mismatch is found.
The program uses a boolean variable isPalindrome to denote whether the string pal is palindrome.
Initially, it is set to true. When a mismatch is detected, isPalindrome
is to false and the loop is terminated with a break statement.


▶️ DTube
▶️ IPFS