Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I compare a string and a char array in Java?

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?

like image 754
Laura Canter Avatar asked Jan 10 '13 18:01

Laura Canter


People also ask

Can we compare a char array with string in Java?

you have to convert the character array into String or String to char array and then do the comparision. Save this answer. Show activity on this post. Compares this string to the specified object.

What is a difference between string and char [] in Java?

char is a primitive data type whereas String is a class in java. char represents a single character whereas String can have zero or more characters. So String is an array of chars. We define char in java program using single quote (') whereas we can define String in Java using double quotes (").

Can we compare string and character Java?

You can compare two Strings in Java using the compareTo() method, equals() method or == operator. The compareTo() method compares two strings. The comparison is based on the Unicode value of each character in the strings.

Can we compare array with string?

Of course, you can't compare a String array to an int array, which means two arrays are said to be equal if they are of the same type, has the same length, contains the same elements, and in the same order. Now, you can write your own method for checking array equality or take advantage of Java's rich Collection API.


2 Answers

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

like image 99
PermGenError Avatar answered Sep 30 '22 00:09

PermGenError


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.

like image 30
Fritz Avatar answered Sep 30 '22 01:09

Fritz