Palindrome of string in java
What is Palindrome ?
> A palindrome is number,string or phrase which reads same as backward and forward.Ex-MADAM, 121 etc1ST CLEAR ONE THING THAT A STRING IS A IMMUTABLE CONSTANT IN JAVA. IT MEANS A STRING CAN NOT BE CHANGED. SO WE WILL USE A NEW METHOD WHICH IS CALLED Stringbuffer ,IT IS A STRING BUT IT CAN BE MODIFIED .
Steps to do this:-
1. take 2 string variable named a,b;
2. now take a Scanner class and make an object name s
3. take a word or sentence from user and scan it like
a=s.nextLine();
4. now use StringBuffer class and make a object named sb and pass the scanned user input string as a parameter inside it
StringBuffer sb=new Stringbuffer(a);
remember we scan "a" so we just pass it as a parameter inside StringBuffer.
5. there is many method inside StringBuffer class like
- append()
- reverse()
- insert()
- capacity()
- reverse()
- delete(int start_index,int end_index)
- replace(
int start_index,int end_index , string ) - deleteCharAt(int index)
now do this,
b=sb.reverse().toString();
we just reverse the string and we change it in String Buffer from String so we change the StringBuffer into a string by toString() method
6. check this
if(a.equals(b))
{
print"palindrome"
}
else
{
print "not a palindrome "
}
in here we just check the string is equal or not, and according to palindrome concept if it is equal then it will print the if block otherwise it will print the else block.
7. save and run
The Source Code
import java.util.Scanner;
class palindrome
{
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
String a,b;
System.out.println("enter the word");
a=s.nextLine();
StringBuffer sb=new StringBuffer(a);
b=sb.reverse().toString();
if (a.equals(b))
{
System.out.println("this is palindrome");
}
else
{
System.out.println("this is not a palindrome");
}
}
}
OUTPUT
Watch My Video
Comments
Post a Comment
if you like it or have any doubts please let me know