How to check number is palindrome in java



A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward. To check if a string is a palindrome in Java, you can create a simple program as follows:


public class PalindromeChecker {

public static void main(String[] args) {

String input = "racecar"; // Change this to the string you want to check

if (isPalindrome(input)) {

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

} else {

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

}

}

public static boolean isPalindrome(String str) {

// Remove spaces and convert the string to lowercase

str = str.replaceAll("\\s", "").toLowerCase();

int left = 0;

int right = str.length() - 1;

while (left < right) {

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

return false;

}

left++;

right--;

}

return true;

}

}

This program defines a function isPalindrome that checks if a given string is a palindrome. It first removes spaces and converts the string to lowercase to ensure case-insensitive checks. Then, it uses two pointers (one starting from the beginning and the other from the end) to compare characters in the string. If at any point the characters don't match, it returns false. If the loop completes without finding any mismatches, the string is considered a palindrome, and the function returns true.

You can change the input variable to test the program with different strings.

Tags

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.