1

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"})

Cim Took
  • 153
  • 1
  • 2
  • 9

5 Answers5

3

str is an array of Strings.

To compare the value of Strings, 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; }

Sam
  • 304
  • 1
  • 8
2

see Java String.equals versus ==

You have to use the equals method, not the = operator for comparing strings in java.

Community
  • 1
  • 1
bedane
  • 1,129
  • 11
  • 13
2

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.

Piotr Miś
  • 981
  • 5
  • 6
2

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.

Community
  • 1
  • 1
Christian Semrau
  • 8,913
  • 2
  • 32
  • 39
2

try this instead if (!str[i].equals(str[str.length-1-i]))

gpu3d
  • 1,164
  • 1
  • 10
  • 21