How can I compare string and char array in java?

In my program, I am trying to compare the char asterixA[] array with a string (word) in an if loop:

 if (word.equals(asterixA)) 

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

+7
source share
4 answers

you need to convert the character array to String or String to a char array, and then do the comparison.

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

or

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

BTW. if it is a conditional statement, not a loop

+12
source

It seems that the string โ€œA String is an array of charactersโ€ is too literal. String equals indicates 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 on the circumstances, but usually you are comparing two objects of the same type or two objects belonging to the same hierarchy (sharing a common superclass).

In this case, a String not char[] , but Java provides mechanisms for moving from one to the other, either by converting String -> char[] with String#toCharArray() or char[] -> String by passing char[] as a parameter to the constructor of String .

This way you can compare both objects after turning String to char[] or vice versa.

+1
source

follow these steps: if(word.equals(new String((asterixA))

0
source

You can compare arrays:

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

All Articles