[Fixed] char cannot be dereferenced in java

In this post, we will see how to fix error char cannot be dereferenced in java.


As we know that there are two data types in java

  • primitive such as int, long, char etc
  • Non primitive such as String, Character etc.

One of the common reasons for this error is calling method on a primitive datatype char. As type of char is primitive, it can not dereferenced.

Dereference is process of getting the value referred by a reference. Since char is primitive and already have value, char can not be dereferenced.

Let’s understand this with the help of simple examples:

Example 1 : Calling equals() method on primitive type char

We can get this error while using equals method rather than == to check equality for char.

When you will compile the code, you will get below error:

C:\Users\Arpit\Desktop\javaPrograms>javac CharEqualityCheckMain.java
CharEqualityCheckMain.java:7: error: char cannot be dereferenced
if(c.equals(‘A’))
^
1 error

Solution 1

Replace equals with ==

We can resolve this issue by replacing equals method with ==.

Output:

value of c is A

Using Character.toString() method to convert char to String

We can resolve this issue by calling Character.toString() method to convert char to String and then calling equals method for equality check.

Output:

value of c is A

Example 2 : Calling isLetter() method on primitive type char

You may also get this error when you are trying to call isLetter() method directly on primitive data type char.

When you will compile the code, you will get below error:

C:\Users\Arpit\Desktop\javaPrograms>javac CharIsLetterMain.java
CharIsLetterMain.java:8: error: char cannot be dereferenced
if(c.isLetter())
^
1 error

Solution 2

We are getting this error because we are calling isLetter() method on primitive data type char rather than using `Character.isLetter() method.

Output:

char c is not letter

That’s all about how to fix char cannot be dereferenced in java.

Related Posts

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.