Palindrome Program using While Loop

This is one of the easiest programs to find Palindrome program using 'For Loop'. Let' dive into an example to check whether a given input is a palindrome or not.

public class PalindromeProgram {

public static void main(String[] args) {

int rem, rev= 0, temp;
int n=121; // user defined number to be checked for palindrome

temp = n;

// reversed integer is stored in variable
while( n != 0 )
{
rem= n % 10;
rev= rev * 10 + rem;
n=n/10;
}

// palindrome if orignalInteger(temp) and reversedInteger(rev) are equal
if (temp == rev)
System.out.println(temp + " is a palindrome.");
else
System.out.println(temp + " is not a palindrome.");
}
}

Output: 121 is a palindrome number

Explanation: Input the number you want to check and store it in a temporary(temp) variable. Now reverse the number and compare whether the temp number is same as the reversed number or not. If both the numbers are same, it will print palindrome number, else not a palindrome number.

Note: The logic of the Palindrome program remains the same, but the execution differs.

Now that you are clear with the logic, let's try to implement the palindrome program in Java in another way i.e using while loop.