- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to check a String for palindrome using arrays in java?
To verify whether the given string is a palindrome (using arrays)
- Convert the given string into a character array using the toCharArray() method.
- Make a copy of this array.
- Reverse the array.
- Compare the original array and the reversed array.
- in case of match given string is a palindrome.
Example
import java.util.Arrays; import java.util.Scanner; public class Palindrome { public static void main(String args[]) { System.out.println("Enter a string "); Scanner sc = new Scanner(System.in); String s = sc.nextLine(); char[] myArray = s.toCharArray(); int size = myArray.length; char [] original = Arrays.copyOf(myArray,myArray.length); for (int i = 0; i < size / 2; i++) { char temp = myArray[i]; myArray[i] = myArray[size-i-1]; myArray[size-i-1] = temp; } System.out.println("Original Array"+Arrays.toString(original)); System.out.println("Reverse Array"+Arrays.toString(myArray)); if(Arrays.equals(myArray, original)) { System.out.println("Entered string is a palindrome"); } else { System.out.println("Entered string is not a palindrome"); } } }
Output
Enter a string mam Original Array[m, a, m] Reverse Array[m, a, m] Entered string is a palindrome
Advertisements