How to Fix int cannot be dereferenced Error in Java?

Table of Contents “Int cannot be dereferenced” is an error that occur in java program.Output:How to fix int cannot be dereferenced?Output:Conclusion  “Int cannot be dereferenced” is an error that occur in java program. In java, …

int-cannot-be-dereferenced

“Int cannot be dereferenced” is an error that occur in java program.

In java, there are two types of variables:

  • Objects. 
  • Primitives.

Objects are referenced type variables means they are self-contained components (they have attributes, methods that can be applied and modified), and primitives are simple raw values.

There are eight primitives defined in java:

  • Int
  • byte
  • Boolean
  • double
  • float
  • char
  • long
  • short

Now, let’s see what is int cannot be dereferenced?

To know more, let’s see an example below:



public class MyClass {
    public static void main(String args[]){
    int x=10;
    int y=25;
    int z=x+y;

    System.out.println(z.length);

}

}

Output:
int cannot be dereferenced

Since int is a primitive data type and it cannot be dereferenced directly.

Now, the question arises what is dereferencing?

Dereferencing is a method of accessing already referenced value.

And why is it showing with primitive data type “int”?

Primitives are the raw values. They are not like objects means they do not have methods. So, you cannot write primitive. something().

As in the above example, “z” is an int (primitive) and cannot be dereferenced.

It means primitive anything() is invalid syntax in java, and it will raise errors.

How to fix int cannot be dereferenced?

To fix this, we will correct its syntax and replace z.length with z

Let’s see this in the example below.



public class MyClass {
    public static void main(String args[]){
      int x=10;
      int y=25;
      int z=x+y;

     System.out.println(z);

}

}

Output:

Conclusion 

“int cannot be dereferenced” is an error that raises in java due to invalid syntax. These two variables are used in java objects and primitives. Objects are self-contained components and referenced type variables, and primitives are raw values (int, short, long, float, boolean, char, byte, and double). In java, we cannot write primitive something(). If we write it, it will show us the error “int cannot be dereferenced.” We can solve this by fixing its syntax. Showed in the above example.

Leave a Comment