Quoted below is the description of String#substring(int beginIndex, int endIndex)
:
Returns a new string that is a substring of this string. The substring
begins at the specified beginIndex and extends to the character at
index endIndex - 1. Thus the length of the substring is
endIndex-beginIndex.
Thus, in order to get a string of just one character using String#substring(int beginIndex, int endIndex)
, the value of endIndex
needs to be equal to beginIndex + 1
e.g. "Hello".substring(1, 2)
is equivalent to String.valueOf("Hello".charAt(1))
.
Demo:
public class Main {
public static void main(String[] args) {
// Test strings
String[] arr = { "dad", "malayalam", "papa" };
for (String s : arr) {
System.out.println(isPallindrome(s));
}
}
static boolean isPallindrome(String s) {
int len = s.length();
for (int i = 0; i < len / 2; i++) {
if (!s.substring(i, i + 1).equals(s.substring(len - i - 1, len - i))) {
return false;
}
}
return true;
}
}
Output:
true
true
false