Display string palindrome in java using for loop
A string is said to be a palindrome if it is the same if we start reading it from left to right or right to left. So let us consider a string “str”, now the task is just to find out with its reverse string is the same as it is.
Input : str = “radar”
Output: Yes
Example 1:
To find the a Palindrome in Java. There is simple method, we will first reverse the string or number and compare the reversed string or number with the original value.
class Main {
public static void main(String[] args) {
String str = "Radar", reverseStr = "";
int strLength = str.length();
for (int i = (strLength - 1); i >=0; --i) {
reverseStr = reverseStr + str.charAt(i);
}
if (str.toLowerCase().equals(reverseStr.toLowerCase())) {
System.out.println(str + " is a Palindrome String.");
}
else {
System.out.println(str + " is not a Palindrome String.");
}
}
}
Output:
Radar is a Palindrome String.
Example 2:
This Java program asks the user to provide a string input and checks it for the Palindrome String.
- Scanner class and its function nextLine() is used to obtain the input, and println() function is used to print on the screen.
- Scanner class is a part of java.util package, so we required to import this package in our Java program.
- We also required to create an object of Scanner class to call its functions.
import java.util.Scanner;
class ChkPalindrome
{
public static void main(String args[])
{
String str, rev = "";
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string:");
str = sc.nextLine();
int length = str.length();
for ( int i = length - 1; i >= 0; i-- )
rev = rev + str.charAt(i);
if (str.equals(rev))
System.out.println(str+" is a palindrome");
else
System.out.println(str+" is not a palindrome");
}
}
Output:
Enter a string:
radar
radar is a palindrome
Example 3:
In the below example, we have a number 3553 stored in num and originalNum variables. Here, we have used the
- while loop to reverse num and store the reversed number in reversedNum
- if…else to check if reversedNum is same as the originalNum
class Main {
public static void main(String[] args) {
int num = 3553, reversedNum = 0, remainder;
// store the number to originalNum
int originalNum = num;
// get the reverse of originalNum
// store it in variable
while (num != 0) {
remainder = num % 10;
reversedNum = reversedNum * 10 + remainder;
num /= 10;
}
// check if reversedNum and originalNum are equal
if (originalNum == reversedNum) {
System.out.println(originalNum + " is Palindrome.");
}
else {
System.out.println(originalNum + " is not Palindrome.");
}
}
}
Output:
3553 is Palindrome.
Display string palindrome in java using for loop – Display string palindrome in java using for loop – Display string palindrome in java using for loop – Display string palindrome in java using for loop