1. Primitive DataType
2. Non-primitive DataType
Primitive data types are char, long, short, int, float, boolean, and byte.
Non-primitive data types are Character, String, Arrays, etc. Non-primitive data types are also known as reference types as they refer to objects.
Read Also: int can not be dereferenced error in java
This error is similar to the int can not be dereferenced error in java. Both errors occur when one tries to call the method on the primitive data type.
To get a better understanding of the error, we are sharing the examples below. First, we will produce the error before moving on to the fix.
Example 1: Producing the error by calling the equals() method
We can easily produce this error by calling the equals() method on char primitive data type as shown below. public class JavaHungry { public static void main(String args[]) { char ch = 'J';if (ch.equals('J')){ System.out.println(ch); } } }
Output:
/JavaHungry.java:4: error: char cannot be dereferenced
if (ch.equals('J'))
^
1 error
Solution:
1. The above compilation error can be resolved by using ==(equality operator) instead of equals() method.
public class JavaHungry { public static void main(String args[]) { char ch = 'J';if (ch == 'J'){ System.out.println(ch); } } }
Output:
J
2. By changing char to Character
public class JavaHungry { public static void main(String args[]) {Character ch = 'J';if(ch.equals('J')) { System.out.println(ch); } } }
Output:
J
Example 2: Producing the error by calling isUpperCase() method
As we have already mentioned you will get this error when you will try to call any valid method on the primitive data type such as char.
public class JavaHungry { public static void main(String args[]) { char ch = 'J';if(ch.isUpperCase()){ System.out.println(ch); } } }
Output:
/JavaHungry.java:4: error: char cannot be dereferenced
if(ch.isUpperCase())
^
1 error
Solution:
1. We can get rid of this error by calling isUpperCase() method on the Character class instead of char primitive data type as shown below.
public class JavaHungry { public static void main(String args[]) { char ch = 'J';if(Character.isUpperCase(ch)){ System.out.println(ch); } } }
That's all for today, please mention in comments in case you have any questions related to the error char can not be dereferenced in java.