Palindrome Program in Java

Palindrome Number in Java

In this example, You learn about java program for Palindrome. A Palindrome Number is a number that is same after reverse. Example: 121, 343, 101, etc. also a string can be a palindrome such as COC, www, etc.

Palindrome Number Algorithm

  1. Receive the number to check for palindrome.
  2. Hold number in variable.
  3. Reverse the number and store in temporary variable.
  4. Compare the both hold number and temporary number.
  5. If both are same then, number is palindrome else not a palindrome number.

Here you learn palindrome program in java, You are given a number and the task of the program to check whether number is palindrome or not.


import java.util.*;
public class Palindrome
{
 public static void main(String args[])
 {
    String original, reverse = "";
    Scanner in = new Scanner(System.in);
    System.out.println("Enter a number");
    original = in.nextLine();
    int length = original.length();
    
    for ( int i = length - 1; i >= 0; i-- )
        reverse = reverse + original.charAt(i);
        
    if (original.equals(reverse))
        System.out.println("Entered number is a palindrome.");
    else
        System.out.println("Entered number is not a palindrome.");
 }
}
Output

Enter a number
120

Entered number is not a palindrome.
Palindrome Program in Java

Let's see the another way to do palindrome program in java. In this java program, we will get a number/string then we find middle from length of string and set one pointer at begin of string another at end of string. Now we compare start pointer value with end pointer if both match then increase start pointer, decrease last pointer and continue till both reaches middle if not match then it is not palindrome.

import java.util.*;

public class Palindrome
{
 public static void main(String args[])
 {
    String inputString;
    Scanner in = new Scanner(System.in);
    System.out.println("Enter a string");
    inputString = in.nextLine();
    int length = inputString.length();
    int i, begin, end, middle;
    begin = 0;
    end = length - 1;
    middle = (begin + end)/2;
    for (i = begin; i <= middle; i++) {
        if (inputString.charAt(begin) == inputString.charAt(end)) {
            begin++;
            end--;
        }
        else {
            break;
        }
    }
    if (i == middle + 1) {
        System.out.println("Palindrome");
    }
    else {
        System.out.println("Not a palindrome");
     }
 }
}
Output

Enter a string
www

Palindrome

Note: You have any problem in the above palindrome number program do not hesitate and write your problem in comment box. I will provide support to your problem.

If you have any doubts, Please let me know

Previous Post Next Post

Contact Form