[Fixed] int cannot be dereferenced in java

In this post, we will see how to resolve error int 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 int. As type of int is primitive, it can not dereferenced.

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

Read also: Char cannot be dereferenced
Let’s understand this with the help of simple examples:

Example 1 : Calling toString() method on primitive type int

Let’s say you want to copy int array to String array and you have written below code:

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

C:\Users\Arpit\Desktop\javaPrograms>javac CopyIntArrayToString.java
CopyIntArrayToString.java:10: error: int cannot be dereferenced
arrStr[i]=arr[i].toString();
^
1 error

Solution 1

We are getting this error because we are calling toString() method on primitive data type int.

There are 2 ways to fix the issue.

Change the int[] array to Integer[]

We can change int[] array to Integer[] to resolve the issue.

Output:

[1, 2, 3]

Cast int to Integer before calling toString() method

We can cast int to Integer to solve int cannot be dereferenced issue.

Output:

[1, 2, 3]

Use Integer.toString()

We can use Integer.toString() method to convert int to String.

Output:

[1, 2, 3]

Example 2 : Calling equals() method on primitive type int

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

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

C:\Users\Arpit\Desktop\javaPrograms>javac IntEqualityCheckMain.java
IntEqualityCheckMain.java:7: error: int cannot be dereferenced
if(i.equals(10))
^
1 error

Solution 2

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

Output:

value of i is 10

That’s all about how to fix int 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.