Palindrome Checker Program: Verify if a String is Palindrome

Check String Length in string is a common operation in Java programming. It helps in various scenarios, such as determining the Counting of a user input or validating the input length against certain criteria. In the following sections, we will explore different approaches to accomplish this task efficiently.

Initializing the String

Before we begin counting the characters, we need to have a string to work with. In Java, you can initialize a string using the String class.

String str= "String is Palendrome";

Using the length() Method

The simplest way to count the characters in a string is by using the length() method provided by the String class. This method returns the number of characters in the string.

str.length();

Using the Condition to check String is boolean

Another approach to count the characters in a string is by using a loop. We can iterate over each character in the string and increment a counter variable.

str = str.toLowerCase(); // Convert the string to lowercase for case-insensitive comparison
int left = 0;
int right = str.length() - 1;

while (left < right) {
if (str.charAt(left) != str.charAt(right)) {
return false;
}
left++;
right--;
}

Performance Considerations

When counting characters in a string, it’s important to consider performance. The length() method has a time complexity of O(1) as it directly returns the length. However, using a loop to count characters has a time complexity of O(n) since it iterates over each character.

Sample code

public class Stringispalendrome{

    public static void main(String[] args) {
        String input = "madam"; // Example input string

        if (isPalindrome(input)) {
            System.out.println("The string is a palindrome.");
        } else {
            System.out.println("The string is not a palindrome.");
        }
    }

    public static boolean isPalindrome(String str) {
        str = str.toLowerCase(); // Convert the string to lowercase for case-insensitive comparison
        int left = 0;
        int right = str.length() - 1;

        while (left < right) {
            if (str.charAt(left) != str.charAt(right)) {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }
}

In this program, we have directly assigned a string to the input variable for demonstration purposes. You can modify the value of input to test different strings. The isPalindrome function is the same as in the previous example, which checks whether the string is a palindrome or not. After calling the function, the program prints the appropriate message based on the result.

Remember to replace the input variable with the string you want to check for palindrome property.