Java Program to check for palindrome.

    A set of characters which is magical like these. If you read from right side or left side, it is similar. These set of characters are called palindrome.

Eg: Noon, refer, level, radar, mom, madam and so on.

Let us create a java program to this concept.

Input: String.

Output: The given string is palindrome or not.

Logic:

  • ·       User enters the input String.
  • ·       A user defined function “isitPalindrome()” gets this input.
  • ·       isitPalinfrome():
  • ·       Here, left and right sides of string is represented as ‘left’ and ‘right’.
  • ·       Both are assigned with values.
  • ·       Using a while loop, a set of statements are repeated until ‘left’ is less than ‘right’.
  • ·       If the left character is not equal to right character, then return false.
  • ·       Otherwise, continue the process. Increase the ‘left’ value by 1 and decrease the ’right’ value by 1.
  • ·       Check for all characters in  left and right, return true when all of these are equal.
  • ·       Main():
  • ·       Read the input string from the user.
  • ·       Call the function isitPalindrome().
  • ·       Check the return value from the function. if it is true, print the string is a palindrome.
  • ·       Else, print the string is not a palindrome.

Program:

import java.util.Scanner;

public class PalindromeCheckEg {

    public static boolean isitPalindrome(String str1) {

        int left = 0;

        int right = str1.length() - 1;

         while (left < right) {

            if (str1.charAt(left) != str1.charAt(right)) {

                return false;

            }

            left++;

            right--;

        }

         return true;

    }

     public static void main(String[] args) {

        System.out.println("Java Program to check for palindrome");

        Scanner myObj1 = new Scanner(System.in);

        System.out.println("Enter the input String");

        String input = myObj1.nextLine();

        if (isitPalindrome(input)) {

            System.out.println(input + " is a palindrome.");

        } else {

            System.out.println(input + " is not a palindrome.");

        }

    }

}

Output:

C:\raji\blog>javac PalindromeCheckEg.java

C:\raji\blog>java PalindromeCheckEg

Java Program to check for palindrome

Enter the input String

level

level is a palindrome.

C:\raji\blog>java PalindromeCheckEg

Java Program to check for palindrome

Enter the input String

program

program is not a palindrome.

No comments:

Post a Comment