Palindrome is a popular title for programming training. You may compare a pair of chars in a string, or a pair of words in a String array. Many homeworks are made in this way.
Further more, in Java we may play with all the speaking languages in the world, such as Chinese, Korean, Japanese, Russian, and so on since Java uses Unicode for its char type. I have written a simple program to show the usefulness of both the Java char and the StringBuffer which provides a reverse() method to reverse any string. Please check my code and provide comments.

import java.io.*;
import javax.swing.JOptionPane;
 public class Palindrome{   

 static boolean palindromeCouplet (String s)   {
 	StringBuffer s1 = new StringBuffer(s);
 return ((s.compareTo(new String(s1.reverse()))==0) ? true :false)  ;

 public static void main(String[] args) {	
    String str=JOptionPane.showInputDialog( null,  
	"Type in a word!\nPress cancel to ternimate。",
	if (str == null) {
	System.out.println("Bey for now");
JOptionPane.showMessageDialog( null,  
	"Palindrome: " + palindromeCouplet(str),
	str + " IS A PALIDROME? ",
6 Years
Discussion Span
Last Post by tong1

Using the reverse method sort of defeats the purpose of the exercise, doesn't it? Unless all you want to do with java is call ready-made methods in the built-in classes, I suppose.


jon, thank you for your quick response. You are right for the sake of exercise. For the purpose of exercise we should write our own code as much as possible. But after we made extensive exercises we should definitely know if there is a ready-made method in Java so that in the future, when working in software industry, we may simply use the ready-made methods instead of our-own made if the code we made is not better than the ready-made.

One question for students:
Why class String has no reverse() method?

Edited by tong1: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.