palindrome number in java using string methods code example
Example 1: String palindrome in java using array
import java.util.Arrays;
import java.util.Scanner;
public class StringPalindromeUsingArray
{
public static void main(String[] args)
{
System.out.println("Please enter string to check whether string is palindrome: ");
Scanner sc = new Scanner(System.in);
String strInput = sc.nextLine();
char[] chArray = strInput.toCharArray();
int size = chArray.length;
char[] chGiven = Arrays.copyOf(chArray, chArray.length);
for(int a = 0; a < size / 2; a++)
{
char temp = chArray[a];
chArray[a] = chArray[size - a - 1];
chArray[size - a - 1] = temp;
}
System.out.println("Given array: " + Arrays.toString(chGiven));
System.out.println("String palindrome using array: " + Arrays.toString(chArray));
if(Arrays.equals(chArray, chGiven))
{
System.out.println("string is palindrome.");
}
else
{
System.out.println("string is not a palindrome.");
}
sc.close();
}
}
Example 2: palindrome number in java
import java.util.Scanner;
public class Palindrome
{
public static void main(String args[])
{
int num,temp,reverse=0;
Scanner input=new Scanner(System.in);
num=in.nextInt();
temp=num;
while(temp!=0)
{
int d=temp%10;
reverse=reverse*10+d;
temp/=10;
}
if(reverse==num)
{
System.out.println("Number is palindrome");
}
else
{
System.out.println("Number is not palindrome");
}
}
}