Saturday, April 24, 2010

Java reverse String and simplest palindrome checker  

0 comments

Today, i have learn something new and it's totally simple. Sometime when don't know about that, we will use our way that take a time to complete a simple task. What i learn today is, how to reverse String. The easiest way to reverse a String for example from "i love you" to "uoy ecol i" is using method reverse() in StringBuffer class. It is also very useful especially when you want to create a palindrome checker program. Your program will be the shortest palindrome checker program in the world i think, hehehehe. I have also created a new one before, but it quit long. You can review it byclick here. Now we will go to coding part. I will create two simple programs. Firstly to reverse "i love you" to "uoy evol i". Secondly i will create my shortest palindrome checker program that i ever made. Don't waste our time by hear what i said.


COMPLETE SOURCE CODE FOR : ReverseString.java



  1. public class ReverseString
  2. {
  3. public static void main(String[]args)
  4. {
  5. String a="i love you";
  6. StringBuffer b=new StringBuffer(a);
  7. System.out.println(b.reverse());
  8. }
  9. }



LIKE USUAL, JUST COMPILE AND EXECUTE IT


COMPLETE SOURCE CODE FOR : MySimplestPalindromeChecker.java


  1. import javax.swing.JOptionPane;
  2. public class MySimplestPalindromeChecker
  3. {
  4. public static void main(String[]args)
  5. {
  6. String a=JOptionPane.showInputDialog(null,"What word that you want to check ?","Palindrome Checker",JOptionPane.QUESTION_MESSAGE);
  7. if(a!=null)
  8. {
  9. String b=a;
  10. StringBuffer c=new StringBuffer(b);
  11. if(a.equals(c.reverse().toString()))
  12. {
  13. JOptionPane.showMessageDialog(null,"THIS IS A PALINDROME WORD");
  14. }
  15. else
  16. {
  17. JOptionPane.showMessageDialog(null,"THIS IS NOT A PALINDROME WORD");
  18. }
  19. }
  20. }
  21. }

What next?

You can also bookmark this post using your favorite bookmarking service:

Related Posts by Categories



Extension Factory Builder