-
Notifications
You must be signed in to change notification settings - Fork 734
/
Palindrome.java
30 lines (30 loc) · 1.05 KB
/
Palindrome.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import java.util.Scanner;
/** * How to check if String is palindrome in Java * using StringBuffer *
public class Palindrome
{
public static void main(String args[])
{
Scanner reader = new Scanner(System.in);
System.out.println("Please enter a String");
String input = reader.nextLine();
System.out.printf("Is %s a palindrome? : %b %n", input, isPalindrome(input));
System.out.println("Please enter another String");
input = reader.nextLine();
System.out.printf("Is %s a palindrome? : %b %n", input, isPalindrome(input)); reader.close();
}
public static boolean isPalindrome(String input)
{
if (input == null || input.isEmpty())
{
return true;
}
char[] array = input.toCharArray();
StringBuilder sb = new StringBuilder(input.length());
for (int i = input.length() - 1; i >= 0; i--)
{
sb.append(array[i]);
}
String reverseOfString = sb.toString();
return input.equals(reverseOfString);
}
}