Cim Took
Cim Took

Reputation: 153

WHats wrong with this code for palindrome of a string array

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

Answers (5)

gpu3d
gpu3d

Reputation: 1184

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

Upvotes: 2

Christian Semrau
Christian Semrau

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

Sam
Sam

Reputation: 304

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; }

Upvotes: 3

Piotr Miś
Piotr Miś

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

bedane
bedane

Reputation: 1127

see Java String.equals versus ==

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

Upvotes: 2

Related Questions