Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Java, please use array instead of string A palindrome is a string that reads the

ID: 3920484 • Letter: J

Question

Java, please use array instead of string

A palindrome is a string that reads the same forwards or backwards; for example dad, mom, deed (i.e., reversing a palindrome produces the same string). Write a recursive, bool-valued function, isPalindrome that accepts a string and returns whether the string is a palindrome. A string, s, is a palindrome if: s is the empty string or s consists of a single letter (which reads the same back or forward), or the first and last characters of s are the same, and the rest of the string (i.e., the second through next-to-last characters) form a palindrome

Explanation / Answer

Given below is the code for the question. I have given both the methods - one using String and other version using char array.
Use may use whichever method you want.
To indent code in eclipse , select code by pressing ctrl+a and then indent using ctrl+i
Please do rate the answer if it was helpful. Thank you

import java.util.Scanner;

public class Palindrome {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String s;

System.out.println("Enter a string: ");
s = keyboard.nextLine();
System.out.println("Using string method, isPalindrome = " + isPalindrome(s));
System.out.println("Using array method, isPalindrome = " + isPalindrome(s.toCharArray(), 0, s.length()-1));

}

private static boolean isPalindrome(String s){
int len = s.length();
if(len <= 1)
return true;
else if(s.charAt(0) == s.charAt(len-1))
return isPalindrome(s.substring(1, len-1));
else
return false;
}

private static boolean isPalindrome(char[] s, int start, int end){
if(start >= end)
return true;
else if(s[start] == s[end])
return isPalindrome(s, start+1, end-1);
else
return false;
}
}


output
=====
Enter a string:
dad
Using string method, isPalindrome = true
Using array method, isPalindrome = true

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote