In the if statement in my User class it says cannot invoke equals(String) on the primitive type char what is the problem?
Asked
Active
Viewed 1,990 times
-2
-
11) Do not post images of code. Please post them here. 2) A char is not a String. It must be `firstLetter == 'R'` – Thiyagu Dec 28 '19 at 04:13
-
you cannot compare String with Char – dassum Dec 28 '19 at 04:14
-
1Uset7 is right, you should post code instead of screenshots. You can compare it like firstLetter.equals("R".charAt(0)); or you should do userInput.startsWith("R"); – Kalpesh Kundanani Dec 28 '19 at 04:25
-
The duplicate question isn't perfect but it outlines what matters here: that you can't invoke methods on primitive types in Java. As the error message tells you. – GhostCat Dec 28 '19 at 04:34
-
In Java, when you use ```"R" ``` (doublequotes) then they are strings and when you use ```'R'```(single quotes) then they are characters. In your code you are trying to compare a character with a string which you embed in double quotes. so first remove the double quotes and replace with single quotes. And next chars are not Objects and so you cannot use equals method to compare them. So you need to use ```==``` to compare two characters. – Brooklyn99 Dec 28 '19 at 04:43
-
now it says incompatible operand types char and string – Matthew Lumpkin Dec 28 '19 at 04:51
-
equals is the method which other classes **inherits** from Object class. Object is the **top most class in the hierarchy of the classes**. Though the primitive types in java are not a class objects hence they **don't inherit** functions from Object class. Also as you are using eclipse it must show you the **reason of compilation errors** upfront. – Saurav Kumar Singh Dec 28 '19 at 04:59
-
Another way is `userInput.startsWith("R") || userInput.startsWith("S") || userInput.startsWith("P")` (dropping the use of `char` completely). One difference is that this will also work with empty user input. In Java a `char` can never be equal to a `String` (there are other languages where they can be equal). – Ole V.V. Dec 28 '19 at 08:28
1 Answers
1
Because the equals() method is method of the Object class and a char is not an object, it is a primitive. In your code, instead of using equals(), you may use == operator to compare with another char primitive. For example, you the following the following in your if clause :
firstLetter == 'R' || firstLetter == 'P' || firstLetter == 'S'

AskAshoke
- 21
- 3