WHAT'S NEW?

Interview Program: Check whether the String is Palindrome or not without using StringBuffer

A simple program to find out whether the String is palindrome or not without using StringBuffer class.



Let me break it in simple steps


Step 1: Find the length of the original String using length().

String original="MALAYALAM";
int l=original.length();

Step 2: Declare one more String to hold a reversed value.


String reverse="";

Step 3: Start a for loop in reverse order and make the use of method charAt(); 

In case you don't know the working of charAt() you can check it here. Click Me for charAt() post.

Whatever character you get in the reverse order,store it in reverse String

for(int i=l-1;i>=0;i--)
{
reverse=reverse+ original.charAt(i);
}

Step 4: When the loop ends, you have two String where you can check whether they both match, if they match they are palindrome, else they are not.


if(original.equals(reverse))
{
System.out.println("It is a palindrome");
}
else
{
System.out.println("It is not a palindrome");
}



Now let me put the whole code in one program.

class PalindromeWithoutSB 
{
public static void main(String[] args) 
{
String original="MALAYALAM";
int l=original.length();
String reverse="";

for (int i=l-1;i>=0 ;i-- )
{
reverse=reverse+original.charAt(i);
}
if(original.equals(reverse))
{
System.out.println("It is a palindrome");
}
else
{
System.out.println("It is not a palindrome");
}

}
}

0 comments:

Post a Comment