I’ve just started java, and I am stuck at basic problem of to check palindrome of string. I have come up with algorithm in which I reverse string then check if(str2.equals(str))
if its palindrome return true
else false
. But I am unable to return boolean in my string function due error
Syntax error on token "String", record expected
I tried typecasting but its not working. What is best way to return boolean or any other data type in another data type?
package fundamentals;
import java.util.*;
public class TestClass {
public static boolean checkPalindrome(String str, String str2)
{if(str2.equals(str)) {
return true;
}
return false;
}
//
public static String reverseString(String str) {
//Your code goes here
String str2 = new String();
int len = str.length();
for(int i=len;i>0;i--)
{
Character temp = str.charAt(i-1);
str2= str2+temp;
temp = null;
}
boolean ans = checkPalindrome(str,str2);
return ans;
}
public static void main (String[] args) {
Scanner s =new Scanner(System.in);
String str = new String();
str = s.next();
System.out.println(reverseString(str));
// System.out.println(str);
//
// for(int i=0;i<str.length();i++)
// {
// char ch = str.charAt(i);
//
// System.out.println(ch);
//
// }
//
}
}
>Solution :
if you want to convert boolean to string, u can use the inbuilt Boolean.toString(boolean b) method
Here is the link to the doccumentation:
https://www.tutorialspoint.com/java/lang/boolean_tostring_boolean.htm#:~:text=toString(boolean%20b)%20returns%20a,%22false%22%20will%20be%20returned.