Solve Error “char cannot be dereferenced” in Java

Are you facing the error char cannot be dereferenced”?

So in this article, we’re going to see the main reason behind this error (char cannot be dereferenced) and the possible solutions.

As we know there are two types of data types – Primitive (i.e. byte, int, boolean) and Non-primitive (ie. Arrays, String). char is a primitive data type, unlike String. So one of the most common reasons for this error is calling a method of String on a char value.

Let’s jump to examples:

Example 1:

The above code will throw the error char cannot be dereferenced” because we’re trying to call equals method on a char data type variable. Which doesn’t exist.

Solution 1:

Instead of calling equals method, we can compare a character using “==”.

But in any case, if you want to use the equals method only then you can convert the character into a String using toString() method of Character class.

Solution 2:

Example 2:

Here we can get confused that we’re applying the equals method on String, but this is not the case because charAt method of String returns a char data type value. So again you can use the Character class and convert the coming value into a String or we can use the “==” operator.

Solution:

It’s pretty normal to get confused with those methods of String and we couldn’t differentiate between the two char and String. So from the next time make sure you’re not doing this mistake otherwise it will lead to the error char cannot be dereferenced”.

One of the easiest ways to prevent this error is to use any IDE or text editor with intellisense on. i.e VS Code, Intellij, and eclipse. Because you will see the error as soon as you type the String’s method name on a character type value.

Leave a Comment

Your email address will not be published. Required fields are marked *