I have written the code to check whether the given string is palindrome or not. But here I didn't create any String object explicitly. When we don't create explicitly, "==" also should work to compare the strings. But here I am not getting correct output if I use ==. For the clarity in my question, I have given another code also below
Code 1:Here. "==" is not working.
class Palindrome
{
public static void main(String[] args)
{
StringBuffer sb1=new StringBuffer();
sb1.append("anna");
String s1=sb1.toString();
StringBuffer sb2=new StringBuffer();
sb2=sb1.reverse();
String s2=sb2.toString();
if(s1.equals(s2))
{
System.out.println("The given String is a Palindrome");
}
else
System.out.println("Not a Palindrome");
}
}
Code 2: Here == works
class Stringdemo
{
public static void main(String[] args)
{
String str1="hello";
String str2="hello";
if(str1==str2)
{
System.out.println("both strings are same");
}
else
{
System.out.println("both strings are not Same");
}
}
}