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:
class Demo{ public static void main(String arg[]){ char ch = 'A'; System.out.println(ch.equals('a')); } }
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:
class Demo{ public static void main(String arg[]){ char ch = 'A'; System.out.println(ch == 'a'); } }
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:
class Demo{ public static void main(String arg[]){ char ch = 'A'; System.out.println(Character.toString(ch).equals("A")); } }
Example 2:
class Demo{ public static void main(String arg[]){ String s = "The crazy programmer"; System.out.println(s.charAt(4).equals('c')); } }
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:
class Demo{ public static void main(String arg[]){ String s = "The crazy programmer"; System.out.println(s.charAt(4) == 'c'); } }
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.