Example Application: Finding a Palindrome



A palindrome is a word or a sentence that reads the same way from left to right or from right to left.

This is an example code of finding out whether a word or sentence is a palindrome. This code uses recursion:

/* File:       Exercise.java
 * Author:     
 * Date:       Friday, March 06, 2009
 * Class:      CMSC 230
 * Purpose:    This application is used to determine whether s string
 *             is a palindrome

package Palindrome2;
import java.util.Scanner;

public class Main {

    // This method uses recursion to analyze a string
    // and find out whether it is a palindrome
    private static boolean recursive(String strSubmitted) {
        if(strSubmitted.length() == 1)
            return true;
        else {
            if(strSubmitted.charAt(0) ==
                    strSubmitted.charAt(strSubmitted.length() - 1)) {
                return recursive(strSubmitted.substring(1,
                        strSubmitted.length() - 1));
                return false;
    public static void main(String[] args) {
        // This variable will be used to hold the result of a method
        boolean is = false;
        // This is the value the user will enter
        String sentence = "";
        // A Scanner object will be used to request a value from the user
        Scanner scnr = new Scanner(System.in);
        // Request a string from the user
        System.out.print("Enter a word or a sentence: ");
        sentence = scnr.nextLine();
        is = iterative(sentence.toLowerCase());
        // Find out whether the user-entered string was a palindrome
        // Display the result accordingly
        if(is == true)
            System.out.println(sentence + " is a palindrome.");
            System.out.println(sentence + " is not a palindrome.");



Home Copyright © 2009-2015, FunctionX, Inc.