8

In my program I'm trying to compare my char array asterixA[] to a String word in an if condition like:

if (word.equals(asterixA))

but it's giving me an error. Is there any other way I can compare them?

2
  • 5
    Convert the char[] into a String, and then use equals. Commented Jan 10, 2013 at 18:29
  • 1
    Make it a habit to go through the Javadocs. It'll help you deal with such things. Commented Jan 10, 2013 at 18:32

4 Answers 4

18

you have to convert the character array into String or String to char array and then do the comparision.

if (word.equals(new String(asterixA)))

or

if(Arrays.equals(word.toCharArray(), asterixA))

BTW. if is a conditional statement not a loop

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, still pretty new to this
1

You seem to be taking the "A String is an array of chars" line too literal. String's equals method states that

Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.

It all depends of the circumstances, but generally you compare two objects of the same type or two objects belonging to the same hierarchy (sharing a common superclass).

In this case a String is not a char[], but Java provides mechanisms to go from one to the other, either by doing a String -> char[] transformation with String#toCharArray() or a char[] -> String transformation by passing the char[] as a parameter to String's constructor.

This way you can compare both objects after either turning your String into a char[] or vice-versa.

Comments

0

You can compare the arrays:

if (Arrays.equals(asterixA, word.toCharArray()) {}

Comments

0

do as follows: if (word.equals(new String(asterixA))) { ... }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.