palindrome string in java with a fixed length code example

Example 1: 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;
    //code to reverse the number
    while(temp!=0)
    {
      int d=temp%10; //extracts digit at the end
      reverse=reverse*10+d;
      temp/=10; //removes the digit at the end
    }
    // 'reverse' has the reverse version of the actual input, so we check
    if(reverse==num)
    {
      System.out.println("Number is palindrome");
    }
    else
    {
      System.out.println("Number is not palindrome");
    }
  }
}

Example 2: palindrome in java

package test
//The function below checks if a string is a palindrome
//True = Is a palindrome & False = Not a palindrome
	public boolean isPalindromString(String text){
    	String reverse = reverse(text);
      	if(text.equals(reverse))
    	{
        	return true;
      	}
      
      	return false;
    }
//This function returns the reverse String of its input.
//Ex. if given "hello", it will return "olleh"
	public String reverse(String input)
    {     
		if(input == null || input.isEmpty())
        {
			return input;
        }
return input.charAt(input.length()- 1) + reverse
                         (input.substring(0, input.length() - 1));
    }

Tags:

Java Example