Reputation: 153
Write a method isPalindrome that accepts an array of Strings as its argument and returns true if that array is a palindrome (if it reads the same forwards as backwards) and /false if not. For example, the array {"alpha", "beta", "gamma", "delta", "gamma", "beta", "alpha"} is a palindrome, so passing that array to your method would return true. Arrays with zero or one element are considered to be palindromes.
public boolean isPalindrome(String[] str){
for (int i =0;i<str.length;i++){
if (str[i]!=str[str.length-1-i])
return false;
}
return true;
}
It fails for the inputs according to a practice website answers.
isPalindrome({"aay", "bee", "cee", "cee", "bee", "aay"})
isPalindrome({"aay", "bee", "cee", "cee", "bee", "aay"})
Upvotes: 1
Views: 1308
Reputation: 9013
This code is comparing strings using ==
, which performs an identity comparison on objects. You need to compare strings using string1.equals(string2)
to check for content equality.
The method fails for the input isPalindrome({"a", "aa".substring(1)})
, because the two strings are equal, but not identical.
For more details, check out How do I compare strings in Java? which contains some more examples.
Upvotes: 2
Reputation: 304
str
is an array of String
s.
To compare the value of String
s, you have to use String.equals
- the ==
operator compares the identity of the string and not the value itself.
public boolean isPalindrome(String[] str){
for (int i=0;i<str.length;i++){
if (!str[i].equals(str[str.length - i - 1])) return false;
}
return true;
}
Upvotes: 3
Reputation: 981
Strings in Java are treated like other objects - comapring with !=
compares the references, not the values. For value comparison you need to use String.equals
method.
Upvotes: 2
Reputation: 1127
see Java String.equals versus ==
You have to use the equals method, not the = operator for comparing strings in java.
Upvotes: 2