Introduction
A palindrome is a string that reads the same backward as forward. For example, “radar” and “level” are palindromes. Palindrome checking is a common problem in programming that helps in understanding string manipulation and control flow in code.
Objective
The objective of this program is to determine whether a given string is a palindrome. This will be achieved by comparing characters from the start and end of the string, moving towards the center.
Java Code
public class PalindromeChecker {
public static void main(String[] args) {
String input = "radar"; // Change this input to test with different strings
boolean isPalindrome = checkPalindrome(input);
if (isPalindrome) {
System.out.println(input + " is a palindrome.");
} else {
System.out.println(input + " is not a palindrome.");
}
}
public static boolean checkPalindrome(String str) {
int left = 0;
int right = str.length() - 1;
while (left < right) {
if (str.charAt(left) != str.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
}
Program Structure
The program consists of a main class called PalindromeChecker
with the following components:
- main method: This is the entry point of the program where we define the input string and call the
checkPalindrome
method. - checkPalindrome method: This method takes a string as input and checks if it is a palindrome by using a two-pointer approach.
How to Run the Program
- Ensure you have Java Development Kit (JDK) installed on your machine.
- Create a new Java file named
PalindromeChecker.java
and copy the provided code into the file. - Open a terminal or command prompt.
- Navigate to the directory where the
PalindromeChecker.java
file is located. - Compile the program using the command:
javac PalindromeChecker.java
- Run the compiled program using the command:
java PalindromeChecker
- Observe the output in the terminal, which will indicate whether the input string is a palindrome.
Conclusion
This program effectively checks if a string is a palindrome, demonstrating the use of string manipulation and logical conditions in Java.