Imagine I have a String array 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));
}
it 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'));
}
it will print:
true
false
true
So here is my question. Is it possible to use charAt and equals on the same line, I mean, something like this:
System.out.println((fruits[i][0].charAt(1)).equals("r"));
Regards,
favolas
Yes, provided you convert the result of
charAt()toCharacterfirst:A simpler version is to write
I personally would always prefer the latter to the former.
The reason your version doesn’t work is that
charAt()returnschar(as opposed toCharacter), andchar, being a primitive type, has noequals()method.Another error in your code is the use of double quotes in
equals("r"). Sadly, this one would compile and could lead to a painful debugging session. With thechar-based version above this would be caught at compile time.