ISC Practicals and Theory - Palindrome Word/Sentence
Updated 21 Oct 2026
This program reads a sentence ending in a full stop, question mark or exclamation mark. It prints every word that is a palindrome, the number of such words, and whether the whole sentence is itself a palindrome. The words are cut out of the sentence with charAt() and substring(), without split() or StringTokenizer. Everything is written in the main method.
Definition
A palindrome reads the same from left to right and from right to left, e.g. Madam, level, a.
- Word level:
Nitinis a palindrome (N-i-t-i-n against n-i-t-i-N, ignoring case);ranis not. A word of one letter, likeaorI, is a palindrome. - Sentence level: ignoring spaces, the terminator and case,
Never odd or even.becomesneveroddoreven, which reads the same both ways, so the sentence is a palindrome (though none of its words is).
Choices made in this program:
- Spaces at the two ends of the line are ignored: the program removes them with
trim(). The sentence is then valid only if its last character is.,?or!and at least one character comes before it. Anything else printsINVALID INPUT. - Words are separated by spaces only, and any other character (a comma, for example) is treated as part of the word. For the whole-sentence test only spaces and the final terminator are ignored.
- Characters are compared case-insensitively by turning small letters into capitals with ASCII arithmetic, not with
equalsIgnoreCase()ortoLowerCase(). No library method that reverses a string is used. - Single-letter words are counted as palindromes.
- A sentence made only of the terminator (
.) has no words, so it isINVALID INPUT.
Algorithm
- Read the sentence into
strand remove the spaces at its two ends withtrim(). It is valid only if it has at least 2 characters and ends in.,?or!; otherwise printINVALID INPUTand stop. - Set
result = ""andcount = 0, and letnbe the position of the terminator (str.length() - 1). - Cut out the words: with
ifrom 0, skip a space; otherwisejmoves to the end of the word, andw = str.substring(i, j)is the word. Then continue fromi = j. - Test each word
wwith two pointers,afrom the left end andbfrom the right end. Both characters are brought to capitals (a small letter has its ASCII value reduced by 32) so that the case is ignored. If any pair differs, setpal = false. A one-letter word is a palindrome. - If
palis true, add the word and a space toresultand add 1 tocount. - Print the palindrome words (or
none) andcount. - To test the whole sentence, move
ifrom the left end andjfrom the right end (before the terminator). A space on either side is skipped; the other characters are compared, ignoring the case, andspalbecomes false at the first difference. Print whether the sentence is a palindrome.
Program
In main, the first while loop cuts out the words and tests each with two pointers; the last while loop tests the whole sentence in the same way, skipping spaces.
import java.util.Scanner;
/* Program PalindromeWords reads a sentence, displays the words that are palindromes
and checks whether the whole sentence is one. */
public class PalindromeWords
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String str = sc.nextLine().trim(); // trim() removes the spaces at the two ends
int n = str.length();
boolean valid = false; // true if there is a word and a terminator . ? or !
if (n >= 2) // empty, or only a terminator, is invalid
{
char last = str.charAt(n - 1);
valid = last == '.' || last == '?' || last == '!';
}
if (!valid)
{
System.out.println("INVALID INPUT");
return;
}
String result = ""; // the palindrome words found, each followed by a space
int count = 0; // number of palindrome words found
n = n - 1; // position of the terminator
int i = 0;
while (i < n)
{
if (str.charAt(i) == ' ') // skip spaces between words
i++;
else
{
int j = i; // j will stop just after the word
while (j < n && str.charAt(j) != ' ')
j++;
String w = str.substring(i, j); // the word
boolean pal = true; // stays true if the word reads the same both ways
int a = 0; // moves from the left end of the word
int b = w.length() - 1; // moves from the right end of the word
while (a < b)
{
char x = w.charAt(a), y = w.charAt(b);
if (x >= 'a' && x <= 'z') // bring small letters to capitals to ignore the case
x = (char) (x - 32);
if (y >= 'a' && y <= 'z')
y = (char) (y - 32);
if (x != y)
pal = false; // a mismatch: not a palindrome
a++;
b--;
}
if (pal)
{
result = result + w + " ";
count++;
}
i = j; // continue after this word
}
}
if (count == 0)
System.out.println("Palindrome words: none");
else
System.out.println("Palindrome words: " + result);
System.out.println("Number of palindrome words = " + count);
// the whole sentence: ignoring spaces and case, it must read the same from both ends
boolean spal = true; // stays true if the sentence is a palindrome
i = 0; // moves from the left end
int j = str.length() - 2; // moves from the right, before the terminator
while (i < j)
{
if (str.charAt(i) == ' ')
i++; // skip a space on the left
else if (str.charAt(j) == ' ')
j--; // skip a space on the right
else
{
char x = str.charAt(i), y = str.charAt(j);
if (x >= 'a' && x <= 'z')
x = (char) (x - 32);
if (y >= 'a' && y <= 'z')
y = (char) (y - 32);
if (x != y)
spal = false;
i++;
j--;
}
}
if (spal)
System.out.println("The sentence is a palindrome");
else
System.out.println("The sentence is not a palindrome");
}
}Variable description table
| Variable | Data Type | Purpose |
|---|---|---|
args | String[] | Command line arguments of main; not used |
sc | Scanner | Reads the input typed by the user |
str | String | The sentence typed by the user, after trim() |
n | int | Length of str, then the position of the terminator |
valid | boolean | True if the sentence has a word and ends with ., ? or ! |
last | char | The last character of the sentence, the terminator |
result | String | The palindrome words found, each followed by a space |
count | int | Number of palindrome words found |
i | int | Index in str from which the next word is looked for; later the left pointer for the whole sentence |
j | int | Index just after the current word; later the right pointer for the whole sentence |
w | String | The word being tested |
pal | boolean | Stays true while the word w reads the same from both ends |
a | int | Pointer moving from the left end of w |
b | int | Pointer moving from the right end of w |
x | char | Character at the left pointer, changed to a capital if it is small |
y | char | Character at the right pointer, changed to a capital if it is small |
spal | boolean | Stays true while the whole sentence reads the same from both ends |
Sample input and output
Sample 1
Enter a sentence: Nitin ran.
Palindrome words: Nitin
Number of palindrome words = 1
The sentence is not a palindromeSample 2
Enter a sentence: Never odd or even.
Palindrome words: none
Number of palindrome words = 0
The sentence is a palindromeSample 3
Enter a sentence: I am not a Bob?
Palindrome words: I a Bob
Number of palindrome words = 3
The sentence is not a palindromeSample 4
Enter a sentence: Madam
INVALID INPUTSample 5
Enter a sentence: .
INVALID INPUTSample 6
Enter a sentence: Nitin ran.
Palindrome words: Nitin
Number of palindrome words = 1
The sentence is not a palindromeDry run
Input Nitin ran. (10 characters, so the terminator is at position 9 and n = 9). result is empty and count is 0.
i | j | w | Palindrome? | result | count |
|---|---|---|---|---|---|
| 0 | 5 | Nitin | true: N=n, i=i, t is the middle | Nitin | 1 |
| 5 | str.charAt(5) is a space, so i becomes 6 | Nitin | 1 | ||
| 6 | 9 | ran | false: r and n differ | Nitin | 1 |
| 9 | i is not less than n, loop ends | Nitin | 1 |
So the output is Palindrome words: Nitin and Number of palindrome words = 1.
For the whole sentence, i = 0 and j = 8. N and n match (case ignored), so i = 1 and j = 7. Now i and a differ, so spal becomes false and the program prints The sentence is not a palindrome. This is the same as the real run above.
Variations
- Palindrome String "Write a program to check whether a string is a palindrome using recursive technique." See Palindrome String; this note uses a loop, not recursion.
- Reverse the words "Write a program to accept a sentence and print its words in reverse order."
- Palindrome word "Write a program to accept a word and check whether it is a palindrome."
- Longest palindrome word "Write a program to accept a sentence and print the longest palindrome word in it."