I am getting one String value by using Scanner class in Java. Value stores in the field "name". I am using StringBuilder class for my logical operation and it finally stores one string value. The field name is "sb". At last, both the field holds the same value. I tried to compare the values by using .equals() and it didn't help me. Kindly refer the code on below and please help me to overcome this issue.
public static void main(String[] args) {
System.out.println("Enter String: ");
String name = new Scanner(System.in).nextLine();
StringBuilder sb = new StringBuilder();
for (int i = name.length() - 1; i >= 0; i--) {
sb.append(name.charAt(i));
}
System.out.println(name);
System.out.println(sb);
if (name.equals(sb)) {
System.out.println(name + " --> Palindrome");
} else {
System.out.println(name + " --> Not a Palindrome");
}
}
Output:
Enter String:
madam
madam
madam
madam --> Not a Palindrome