Skip to main content

Check if String is Palindrome in Java

Let us check if the string is a palindrome in Java. The idea is common, and the implementation is simple.These few lines will check the string is palindrome or not.

 import java.util.*;
class PalindromeString

    public static void main(String args[])
    // Create a Scanner object
    Scanner s=new Scanner(;

    System.out.println("Enter the string");

    // Read the data
    String st1=s.nextLine();

    // Create StringBuffer obj for st1
    StringBuffer sb=new StringBuffer(st1);

    // Reverse the letters

        // Check & Print if palindrome
        System.out.println("Palindrome String");




Create a StringBuffer object. For the st1because the reverse()method is in StringBuffer.
sb.reverse() Reverse the string associated with StringBuffer object.
st1.equals(sb.toString()) Convert StringBuffer object to String type for checking equality using equals() method.

Other way.. It is manually reversing the string by a simple logic without need of creating a StringBuffer object.

In this way, we can simply check if the given string is palindrome or not in Java. Comment.


Popular posts from this blog

Setting Background Image in JFrame - Swing

Here is sample tutorial, a simple trick that enables you to set background image for JFrame.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class BackgroundImageJFrame extends JFrame
JButton b1;
JLabel l1;
public BackgroundImageJFrame()
setTitle("Background Color for JFrame");
One way
setLayout(new BorderLayout());
JLabel background=new JLabel(new ImageIcon("C:\\Users\\Computer\\Downloads\\colorful design.png"));
background.setLayout(new FlowLayout());
l1=new JLabel("Here is a button");
b1=new JButton("I am a button");
// Another way
setLayout(new BorderLayout());
setContentPane(new JLabel(new ImageIcon("C:\\Users\\Computer\\Downloads\\colorful design.png")));
setLayout(new FlowLayout());
l1=new JLabel("Here is a button");
b1=new JButton("I am …

Add two numbers in JSP easily

Here is an example on adding up two numbers in JSP. This is very simple as you see below. This requires very small piece of code. All i have done here is created a HTML file containing the input fields which contain the numbers to add up.Now the values in the input field are of type String, so i have done type casting and converted them into int using Integer.parseInt(). See how easy it looks.

Catch The Rat: Simple Game in Java

A simple, shortest and easiest game that could be written in Java using Swing components and event handling.