Java compares char with string array

Imagine I have an array of strings like this:

String[][] fruits = {{"Orange","1"}, {"Apple","2"}, {"Arancia","3"}; 

If I do this:

  for (int i = 0; i < fruits.length;i++){ System.out.println(fruits[i][0].charAt(1)); } 

he will print:

 r p r 

And if I do this:

  for (int i = 0; i < fruits.length;i++){ Character compare = fruits[i][0].charAt(1); System.out.println(compare.equals('r')); } 

he will print:

 true false true 

So here is my question. Is it possible to use charAt and equal on the same line, I mean, something like this:

 System.out.println((fruits[i][0].charAt(1)).equals("r")); 

Hello,

favolas

+4
source share
3 answers

Yes, if you first convert the result of charAt() to Character :

 System.out.println(Character.valueOf(fruits[i][0].charAt(1)).equals('r')); 

A simpler version is to write

 System.out.println(fruits[i][0].charAt(1) == 'r'); 

I personally would always prefer the latter to the latter.

The reason your version does not work is because charAt() returns char (unlike Character ), and char , being a primitive type, does not have an equals() method.

Another mistake in your code is the use of double quotes in equals("r") . Unfortunately, this one will compile and can lead to a painful debugging session. With the char based version above, this will be detected at compile time.

+7
source

Sure! Try the following:

 System.out.println((fruits[i][0].charAt(1)) == 'r'); 

We are doing a primitive comparison (char to char), so we can use == instead of .equals (). Please note that this is case sensitive.

Another option is to explicitly use char in String before using .equals ()

If you are using a modern version of Java, you can also use the extended syntax for cleaner code, for example:

 public static void main(String[] args) { String[][] fruits = {{"Orange","1"}, {"Apple","2"}, {"Arancia","3"}}; for (String[] fruit: fruits){ System.out.println((fruit[0].charAt(1)) == 'r'); } } 
+4
source

The char data type that is returned from String.charAt() is primitive, not an object. Therefore, you can simply use the == operator to perform the comparison, since it will compare the value, not the link.

 System.out.println((fruits[i][0].charAt(1) == 'r')); 
0
source

All Articles