Error int cannot be dereferenced

I'm fairly new to Java and I'm using BlueJ. I keep getting this "Int cannot be dereferenced" error when trying to compile and I'm not sure what the problem is. The error is specifically happening ...

I’m fairly new to Java and I’m using BlueJ. I keep getting this «Int cannot be dereferenced» error when trying to compile and I’m not sure what the problem is. The error is specifically happening in my if statement at the bottom, where it says «equals» is an error and «int cannot be dereferenced.» Hope to get some assistance as I have no idea what to do. Thank you in advance!

public class Catalog {
    private Item[] list;
    private int size;

    // Construct an empty catalog with the specified capacity.
    public Catalog(int max) {
        list = new Item[max];
        size = 0;
    }

    // Insert a new item into the catalog.
    // Throw a CatalogFull exception if the catalog is full.
    public void insert(Item obj) throws CatalogFull {
        if (list.length == size) {
            throw new CatalogFull();
        }
        list[size] = obj;
        ++size;
    }

    // Search the catalog for the item whose item number
    // is the parameter id.  Return the matching object 
    // if the search succeeds.  Throw an ItemNotFound
    // exception if the search fails.
    public Item find(int id) throws ItemNotFound {
        for (int pos = 0; pos < size; ++pos){
            if (id.equals(list[pos].getItemNumber())){ //Getting error on "equals"
                return list[pos];
            }
            else {
                throw new ItemNotFound();
            }
        }
    }
}

Sotirios Delimanolis's user avatar

asked Oct 1, 2013 at 6:08

BBladem83's user avatar

1

id is of primitive type int and not an Object. You cannot call methods on a primitive as you are doing here :

id.equals

Try replacing this:

        if (id.equals(list[pos].getItemNumber())){ //Getting error on "equals"

with

        if (id == list[pos].getItemNumber()){ //Getting error on "equals"

answered Oct 1, 2013 at 6:10

Juned Ahsan's user avatar

Juned AhsanJuned Ahsan

67.1k11 gold badges96 silver badges134 bronze badges

2

Basically, you’re trying to use int as if it was an Object, which it isn’t (well…it’s complicated)

id.equals(list[pos].getItemNumber())

Should be…

id == list[pos].getItemNumber()

answered Oct 1, 2013 at 6:10

MadProgrammer's user avatar

MadProgrammerMadProgrammer

340k22 gold badges226 silver badges356 bronze badges

4

Dereferencing is the process of accessing the value referred to by a reference . Since, int is already a value (not a reference), it can not be dereferenced.
so u need to replace your code (.) to(==).

answered Feb 21, 2022 at 5:20

Ashwani Kumar Kushwaha's user avatar

Assuming getItemNumber() returns an int, replace

if (id.equals(list[pos].getItemNumber()))

with

if (id == list[pos].getItemNumber())

answered Oct 1, 2013 at 6:10

John3136's user avatar

John3136John3136

28.6k4 gold badges50 silver badges68 bronze badges

Change

id.equals(list[pos].getItemNumber())

to

id == list[pos].getItemNumber()

For more details, you should learn the difference between the primitive types like int, char, and double and reference types.

answered Oct 1, 2013 at 6:11

Code-Apprentice's user avatar

Code-ApprenticeCode-Apprentice

79.9k21 gold badges140 silver badges256 bronze badges

As your methods an int datatype, you should use «==» instead of equals()

try replacing this
if (id.equals(list[pos].getItemNumber()))

with

if (id.equals==list[pos].getItemNumber())

it will fix the error .

answered Jun 23, 2018 at 14:59

Ashit's user avatar

AshitAshit

596 bronze badges

I think you are getting this error in the initialization of the Integer somewhere

answered Jan 29 at 6:18

Ujjwal Pal's user avatar

1

try

id == list[pos].getItemNumber()

instead of

id.equals(list[pos].getItemNumber()

answered Oct 1, 2013 at 6:12

Ali Hashemi's user avatar

Ali HashemiAli Hashemi

3,0283 gold badges34 silver badges47 bronze badges

Here, we will follow the below-mentioned points to understand and eradicate the error alongside checking the outputs with minor tweaks in our sample code

  • Introduction about the error with example
  • Explanation of dereferencing in detail
  • Finally, how to fix the issue with Example code and output.

If You Got this error while you’re compiling your code? Then by the end of this article, you will get complete knowledge about the error and able to solve your issue, lets start with an example.

Example 1:

Java

import java.io.*;

import java.util.*;

class GFG {

    public static void main(String[] args)

    {

        Scanner sc = new Scanner(System.in);

        int a = sc.nextInt();

        int b = sc.nextInt();

        int sum = a + b;

        System.out.println(sum.length);

    }

}

 Output:

So this is the error that occurs when we try to dereference a primitive. Wait hold on what is dereference now?. Let us do talk about that in detail. In Java there are two different variables are there: 

  1. Primitive [byte, char, short, int, long, float, double, boolean]
  2. Objects

Since primitives are not objects so they actually do not have any member variables/ methods. So one cannot do Primitive.something(). As we can see in the example mentioned above is an integer(int), which is a primitive type, and hence it cannot be dereferenced. This means sum.something() is an INVALID Syntax in Java.

Explanation of Java Dereference and Reference: 

  • Reference: A reference is an address of a variable and which doesn’t hold the direct value hence it is compact. It is used to improve the performance whenever we use large types of data structures to save memory because what happens is we do not give a value directly instead we pass to a reference to the method.
  • Dereference: So Dereference actually returns an original value when a reference is Dereferenced.

What dereference Actually is?

Dereference actually means we access an object from heap memory using a suitable variable. The main theme of Dereferencing is placing the memory address into the reference. Now, let us move to the solution for this error,

How to Fix “int cannot be dereferenced” error?

Note: Before moving to this, to fix the issue in Example 1 we can print, 

System.out.println(sum); // instead of sum.length  

Calling equals() method on the int primitive, we encounter this error usually when we try to use the .equals() method instead of “==” to check the equality.

Example 2: 

Java

public class GFG {

    public static void main(String[] args)

    {

        int gfg = 5;

        if (gfg.equals(5)) {

            System.out.println("The value of gfg is 5");

        }

        else {

            System.out.println("The value of gfg is not 5");

        }

    }

}

Output:

Still, the problem is not fixed. We can fix this issue just by replacing the .equals() method with”==” so let’s implement “==” symbol and try to compile our code.

Example 3:

Java

public class EqualityCheck {

    public static void main(String[] args)

    {

        int gfg = 5;

        if (gfg == 5)

        {

           System.out.println("The value of gfg is 5");

        }

        else

        {

           System.out.println("The value of gfg is not 5");

        }

    }

}

Output

The value of gfg is 5

This is it, how to fix the “int cannot be dereferenced error in Java.

Dereferencing means accessing an object from the heap using a reference variable Or we can say It is a process of accessing the referred value by a reference.

Dereferencing’s main purpose is to place the memory address (where the actual object presents) into the reference.

Example:

Object ob = new Object();

String st = ob.toString(); // ‘ob’ is dereferenced.

If the reference has the null value, at that time the result of dereferencing will be a “Null Pointer Exception.”

Example:

Object ob =null;

Ob.toString();  // when this statement is executed It will throw a NullpointerException.

Reference: A reference is an address of a variable and it is an easy, compact scalar value that’s why it does not contain data directly. It is also used for improve the performance when we are using large types of data structures and it saves memory because instead of passing a single value it passes a reference to a subroutine or method.

Deference: Deference returns a actual value when a reference is dereferenced.

Reference Variables: In java There are two types of variables, primitive types and object types. So the object type of variables called reference variables. Int is a primitive data type, it is not an object or reference. Because int is already a value and not a reference that’s why it can not be dereferenced.

Example:

public class Abc {

public static void main ( String[] args) {

int a=1;

System.out.println(a.length);

}

}

Output:

Abc.java : 5 : error int cannot be dereferenced
System.out.println(x.length);
1 error

In Java programming, there are two different types of variables: primitive data type and object type. The primitive data is different from objects because they do not behave as objects. The primitive data types variable considered as local variables or as a field. it allocates on the stack. And objects always allocates on the heap area. If you are declaring a local variable as an object then it will be allocated in the heap area. The stack only contains the references.

We use reference to store the address to variable or object. If we want to get or set the value for that variable that we have to need de-referenced that it means we need to get memory location where it is actually placed in the memory. “So, we can say that using dot(.) operator, accessing the state or behavior of an object is called dereferencing”.

Here we are taking some possible examples where this error “int cannot be dereferenced” can occur.

Example: 

In this example, we are trying to call a method but id is a primitive type. So we cannot call the methods on a primitive type. That’s why it will through an error that int cannot be dereferenced. Instead of the equals method, we can take “==” operators.

int id = 1;

id.toString();

In this example, we are trying to do the same thing as above. So here, there are several ways to fix this error. If we want to convert int into a String then we could concatenate it with an empty string, or we could use the Integer.toString() method if we want to convert it explicitly.

Solution:

int id = 1;

String i =  id + ;

Or

String i = Integer.toString(id);

Example: 

int id = 111;

System.out.println(id.lenght());

Here, we want to get the length of the value which contains by the “id” variable, So, getting the length of value here we are using length() method but we can not use the method with primitive type so we have to convert it first into the String and after that, we can apply this method on it. To convert it into the String we should follow the same ways as the above example.

Solution :

int id = 111;

String i =  id + «»;

Or

String i = Integer.toString(id);

System.out.println (i.lenght());

Example:

public int example() {

int sum = 0;

for ( int i = 0; i < ar.length; i++);

sum = sum + ar[i];

}

In this example, we have done some mistakes that’s why it will through error that int cannot be dereferenced. So, the first error is I have written “; “ after for loop that is wrong because for loop has a body so we have to open this using braces “ { “ and in the last, we have to close this using “ } “. And the second mistake is we have not declared ar as an Array but we are storing the value in it as Array so we have to declare it otherwise it will through the same error as before.

Solution:

int sum = 0;

int[] ar = new int[5];

for ( int i = 0; i < ar.length; i++) {

sum = sum + ar[i];

}

So I hope, after reading this article you’ve got the idea that why “Int cannot be dereferenced” error occurs and how to solve it.

If you’re still struggling with this error then please let us know in the comment box, we would love to help.

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

Table of Contents

  • Example 1 : Calling toString() method on primitive type int
  • Solution 1
    • Change the int[] array to Integer[]
    • Cast int to Integer before calling toString() method
    • Use Integer.toString()
  • Example 2 : Calling equals() method on primitive type int
  • Solution 2

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:

package org.arpit.java2blog;

public class CopyIntArrayToString {

    public static void main(String[] args) {

        int[] arr=new int[] {1,2,3};

        String[] arrStr=new String[arr.length];

        for (int i=0;i<arr.length;i++)

        {

            arrStr[i]=arr[i].toString();

        }

        System.out.println(Arrays.toString(arrStr));

    }

}

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

C:UsersArpitDesktopjavaPrograms>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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

package org.arpit.java2blog;

import java.util.Arrays;

public class CopyIntArrayToString {

    public static void main(String[] args) {

        Integer[] arr=new Integer[] {1,2,3};

        String[] arrStr=new String[arr.length];

        for (int i=0;i<arr.length;i++)

        {

            arrStr[i]=arr[i].toString();

        }

        System.out.println(Arrays.toString(arrStr));

    }

}

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

package org.arpit.java2blog;

import java.util.Arrays;

public class CopyIntArrayToString {

    public static void main(String[] args) {

        int[] arr=new int[] {1,2,3};

        String[] arrStr=new String[arr.length];

        for (int i=0;i<arr.length;i++)

        {

            arrStr[i]=((Integer)arr[i]).toString();

        }

        System.out.println(Arrays.toString(arrStr));

    }

}

Output:

[1, 2, 3]

Use Integer.toString()

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

package org.arpit.java2blog;

import java.util.Arrays;

public class CopyIntArrayToString {

    public static void main(String[] args) {

        int[] arr=new int[] {1,2,3};

        String[] arrStr=new String[arr.length];

        for (int i=0;i<arr.length;i++)

        {

            arrStr[i]=Integer.toString(arr[i]);

        }

        System.out.println(Arrays.toString(arrStr));

    }

}

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

package org.arpit.java2blog;

public class IntEqualityCheckMain {

    public static void main(String[] args) {

        int i=10;

        if(i.equals(10))

        {

            System.out.println(«value of i is 10»);

        }

        else

        {

            System.out.println(«value of i is not 10»);

        }

    }

}

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

C:UsersArpitDesktopjavaPrograms>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 ==.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

package org.arpit.java2blog;

public class IntEqualityCheckMain {

    public static void main(String[] args) {

        int i=10;

        if(i==10)

        {

            System.out.println(«value of i is 10»);

        }

        else

        {

            System.out.println(«value of i is not 10»);

        }

    }

}

Output:

value of i is 10

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

Содержание

  1. How to Fix int cannot be dereferenced Error in Java?
  2. Solve Error “int cannot be dereferenced” in Java
  3. How to Fix “int cannot be dereferenced” Error?
  4. [Fixed] int cannot be dereferenced in java
  5. Example 1 : Calling toString() method on primitive type int
  6. Solution 1
  7. Change the int[] array to Integer[]
  8. Cast int to Integer before calling toString() method
  9. Use Integer.toString()
  10. Example 2 : Calling equals() method on primitive type int
  11. Solution 2
  12. Was this post helpful?
  13. Share this
  14. report this ad Related Posts
  15. Author
  16. Related Posts
  17. [Fixed] Unsupported class file major version 61 in Java
  18. [Fixed] java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList
  19. [Fixed] java.util.HashMap$Values cannot be cast to class java.util.List
  20. [Fixed] Unable to obtain LocalDateTime from TemporalAccessor
  21. Int cannot be dereferenced: Java
  22. example
  23. output
  24. Java Dereferencing
  25. Solving Int Cannot Be Dereferenced in Java
  26. error: int cannot be dereferenced – on equals
  27. error: int cannot be dereferenced – on compareTo
  28. error: int cannot be dereferenced – on toString
  29. error: int cannot be dereferenced within for loop

How to Fix int cannot be dereferenced Error in Java?

Here, we will follow the below-mentioned points to understand and eradicate the error alongside checking the outputs with minor tweaks in our sample code

  • Introduction about the error with example
  • Explanation of dereferencing in detail
  • Finally, how to fix the issue with Example code and output.

If You Got this error while you’re compiling your code? Then by the end of this article, you will get complete knowledge about the error and able to solve your issue, lets start with an example.

Example 1:

Output:

So this is the error that occurs when we try to dereference a primitive. Wait hold on what is dereference now?. Let us do talk about that in detail. In Java there are two different variables are there:

  1. Primitive [byte, char, short, int, long, float, double, boolean]
  2. Objects

Since primitives are not objects so they actually do not have any member variables/ methods. So one cannot do Primitive.something(). As we can see in the example mentioned above is an integer(int), which is a primitive type, and hence it cannot be dereferenced. This means sum.something() is an INVALID Syntax in Java.

Explanation of Java Dereference and Reference:

  • Reference: A reference is an address of a variable and which doesn’t hold the direct value hence it is compact. It is used to improve the performance whenever we use large types of data structures to save memory because what happens is we do not give a value directly instead we pass to a reference to the method.
  • Dereference: So Dereference actually returns an original value when a reference is Dereferenced.

What dereference Actually is?

Dereference actually means we access an object from heap memory using a suitable variable. The main theme of Dereferencing is placing the memory address into the reference. Now, let us move to the solution for this error,

How to Fix “int cannot be dereferenced” error?

Note: Before moving to this, to fix the issue in Example 1 we can print,

Calling equals() method on the int primitive, we encounter this error usually when we try to use the .equals() method instead of “==” to check the equality.

Источник

Solve Error “int cannot be dereferenced” in Java

Dereferencing means accessing an object from the heap using a reference variable Or we can say It is a process of accessing the referred value by a reference.

Dereferencing’s main purpose is to place the memory address (where the actual object presents) into the reference.

Example:

If the reference has the null value, at that time the result of dereferencing will be a “Null Pointer Exception.”

Example:

Reference: A reference is an address of a variable and it is an easy, compact scalar value that’s why it does not contain data directly. It is also used for improve the performance when we are using large types of data structures and it saves memory because instead of passing a single value it passes a reference to a subroutine or method.

Deference: Deference returns a actual value when a reference is dereferenced.

Reference Variables: In java There are two types of variables, primitive types and object types. So the object type of variables called reference variables. Int is a primitive data type, it is not an object or reference. Because int is already a value and not a reference that’s why it can not be dereferenced.

Example:

Output:

Abc.java : 5 : error int cannot be dereferenced
System.out.println(x.length);
1 error

How to Fix “int cannot be dereferenced” Error?

In Java programming, there are two different types of variables: primitive data type and object type. The primitive data is different from objects because they do not behave as objects. The primitive data types variable considered as local variables or as a field. it allocates on the stack. And objects always allocates on the heap area. If you are declaring a local variable as an object then it will be allocated in the heap area. The stack only contains the references.

We use reference to store the address to variable or object. If we want to get or set the value for that variable that we have to need de-referenced that it means we need to get memory location where it is actually placed in the memory. “So, we can say that using dot(.) operator, accessing the state or behavior of an object is called dereferencing”.

Here we are taking some possible examples where this error “int cannot be dereferenced” can occur.

Источник

[Fixed] int cannot be dereferenced in java

In this post, we will see how to resolve error int cannot be dereferenced 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:

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:

Cast int to Integer before calling toString() method

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

Output:

Use Integer.toString()

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

Output:

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:

Solution 2

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

Output:

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

Was this post helpful?

[Fixed] Invalid method declaration; return type required

[Fixed] char cannot be dereferenced in java

[Fixed] Unsupported class file major version 61 in Java

Table of ContentsReason for Unsupported class file major version 61 in JavaSolution for Unsupported class file major version 61 in JavaAndorid studio/Intellij Idea with gradleAny other scenario In this post, we will see how to fix Unsupported class file major version 61 in Java. Reason for Unsupported class file major version 61 in Java You […]

[Fixed] java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList

Table of ContentsReason for java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayListFixes for java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayListUse ArrayList’s constructorAssign Arrays.asList() to List reference rather than ArrayList In this post, we will see how to fix java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList. ClassCastException is runtime exception which indicate that code has tried to […]

[Fixed] java.util.HashMap$Values cannot be cast to class java.util.List

Table of ContentsWhy HashMap values cannot be cast to list?Fix for java.util.HashMap$Values cannot be cast to class java.util.List In this post, we will see how to fix error java.util.HashMap$Values cannot be cast to class java.util.List. Why HashMap values cannot be cast to list? HashMap values returns java.util.Collection and you can not cast Collection to List […]

[Fixed] Unable to obtain LocalDateTime from TemporalAccessor

Table of ContentsUnable to obtain LocalDateTime from TemporalAccessor : ReasonUnable to obtain LocalDateTime from TemporalAccessor : FixLocalDate’s parse() method with atStartOfDay()Use LocalDate instead of LocalDateTime In this article, we will see how to fix Unable to obtain LocalDateTime from TemporalAccessor in Java 8. Unable to obtain LocalDateTime from TemporalAccessor : Reason You will generally get […]

Источник

Int cannot be dereferenced: Java

Java has two different types of variables: primitive and objects and only objects are reference types. The type int is a primitive and not an object. Dereferencing is the process of accessing the value referred to by a reference . Since, int is already a value (not a reference), it can not be dereferenced.

example

output

Primitives (byte, char, short, int, long, float, double, boolean) are not objects and do not have member variables or methods. They’re just simple values . So you cannot do somePrimitive.something() . So in the above example, x is an int, a primitive, and therefore cannot be dereferenced — meaning x.anything is invalid syntax in Java.

Java Dereferencing

Java has two different types of variables: primitive and objects and only objects are reference types . This means that there are primitive types , originally designed for speed, that do not behave as objects. The primitive types exist either as local variables on the stack, or as fields (static or not) of objects. In Java, objects are always allocated on the heap : if you have a local variable that seems an object, then the object itself is allocated on the heap and the stack contains only a reference, i.e. an additional hidden type that is able to reference, point to, heap memory . Important to note that NOT to stack memory . As a result of this fact, you cannot dereference a primitive type because you cannot create a reference to something different than an object, primitive types are not objects.

In general, Reference is an address to some object/variable, while getting or setting value for that variable you need to de-reference that means you need to get to that location where it is actually laying in the memory. So, we can say that accessing the state or behaviour of an object using its reference with the help of the dot(.) operator is called dereferencing .

Источник

Solving Int Cannot Be Dereferenced in Java

If you are getting “int cannot be dereferenced” error in Java, it means that you are attempting to call a method or an attribute on a int type value. You should note that int is a primitive type and its variables do not store reference, they contain the actual value, so you cannot dereference using int primitive variable unlike wrapper class Integer reference variable.

Above code will give us “int cannot be dereferenced” compile error. Because, variable n is not a reference variable, it is a primitive variable. You can dereference a Integer reference variable, but not using a int type primitive variable.

You might be knowing it already, but sometimes it may happen unknowingly. Let us see few examples.

error: int cannot be dereferenced – on equals

You might be thinking above example would print “true”. Here, we want to convert a number which is in String format to Integer and then compare it with another Integer object. However, we would get “error: int cannot be dereferenced” compile error on equals method. Why? Method parseInt doesn’t return Integer object reference, it returns int value and we cannot call equals method on int. Due to this we get “int cannot be dereferenced”.

You can fix “int cannot be dereferenced” error by replacing parseInt with valueOf as below:

error: int cannot be dereferenced – on compareTo

Here, this code is expecting that parseInt returns Integer and it is attempting to call compareTo method on top of it. But if you check the documentation, parseInt doesn’t return Integer, it returns int type value, and you cannot call methods on int. Initially, it looks like it would print 1. Here, we want to convert a number which is in String format to Integer and then compare it with another Integer object using compareTo method. However, we would get “error: int cannot be dereferenced” compile error on compareTo method as parseInt doesn’t return Integer object reference, it returns int value and we cannot call compareTo method on int.

Similar to the above example, we can fix “int cannot be dereferenced” error by replacing parseInt with valueOf as below:

error: int cannot be dereferenced – on toString

Looking at above code snippet, it appears that we get Integer when calling intValue and we are trying to call toString on top of it. However, we get “int cannot be dereferenced” error on toString method. This is because, intValue doesn’t return Integer, it returns int type value.

To fix this issue, all you need to do is, you can directly call the toString method on top of Integer reference variable as below:

error: int cannot be dereferenced within for loop

This is yet another confusing scenario where you must be iterating over an array thinking that the array is of Integer type only to find that the array is actually of type int primitive type.

Источник

  1. Dereferencing in Java
  2. Cause of int cannot be dereferenced in Java
  3. Solve the int cannot be dereferenced Error in Java

Solve the Int Cannot Be Dereferenced Error in Java

In this article, we’ll discuss the cause of the Java int cannot be dereferenced exception and how to fix it. First, have a look at what dereferencing in Java is.

Dereferencing in Java

Primitive and object variables are the two types of variables that can be used in Java. However, only object variables can be reference types. The int data type is a primitive rather than an object.

Accessing the value that is pointed to by a reference is what’s known as dereferencing. It is impossible to dereference int because it is already a value and is not a reference to anything else.

Cause of int cannot be dereferenced in Java

  1. A reference in Java is an address that points to a specific object or variable. The term dereferencing refers to obtaining an object’s properties through a reference.
  2. If you try to perform any dereferencing on a primitive, like the below example, you will receive the error Z cannot be dereferenced, where Z is a type considered primitive.
  3. The cause for this is that primitives are not the same thing as objects; instead, they are raw value representations.

Solve the int cannot be dereferenced Error in Java

Let’s understand int cannot be dereferenced and figure out how to fix it with the help of the example below:

Example:

public class Main {
 public static void main(String[] args) {
 int Z = 8;
 System.out.println(Z.equals(8));
 }
}

Firstly, we created the Main class and compared an int to a value chosen at random. Z is one of Java’s eight fundamental data types, including int, byte, short, etc.

We will see the following error when we attempt to compile the code:

Main.java:5: error: int cannot be dereferenced
System.out.println(Z.equals(8));
                    ^
1 error

In our case, we need to determine whether or not the two values are equal. Solving our issue is to utilize the notation == rather than the equals() function for primitive types:

public class Main {
 public static void main(String[] args) {
 int Z = 8;
 System.out.println(Z == 8);
 }
}

The following output will be printed when we compile the code:

When we tried to use Primitive types as objects and perform operations on them that are applicable to objects, we ran into dereferenced problems.

Before we get into the specifics of what’s causing the current dereferenced situation, let’s define what dereferenced implies.

When we construct an object, heap memory is allocated and a reference to this heap memory is generated in the stack.

Once we create an object it allocates space in heap memory and a reference is created in the stack pointing to this heap memory. To put it another way, an object reference is used to set or get the values of an object.

However, because a primitive type variable is a value rather than an object, it cannot be used with object methods such as length(), equals(), getClass(), toString(), and other object methods.

It also tells us that everything in java is not an object :)

Let’s look at some common issues that result int cannot be dereferenced and understand the root cause with solutions.


  • How to solve int cannot be dereferenced toString in Java?
  • What is Null pointer dereference?
  • How to fix the dereferenced error with the equals method in java?
  • To brush up on your knowledge on this subject, take the MCQ at the End of this Article.
  • Feedback: Your input is valuable to us. Please provide feedback on this article.

I’m assuming we’re already aware that the toString method converts applied objects to strings. Please take note of the word «applied objects,» which implies that toString should only be used with objects.

To illustrate the reason and possible remedy, consider the following example, which includes generating a dereferenced error.

Solution: int cannot be dereferenced

Explanation :

  • checkMe is an int primitive type that has been defined.
  • Applied toString method on the primitive type.
  • Received dereferenced error because checkMe is not representing reference of object hence it companies and raises an error.

While we develop programs as described above, most of the newer IDEs prompt errors. Using the valueOf method, one of the possible solutions to the above failure is shown below.

int testMe = 10;

System.out.println(Integer.valueOf(testMe).getClass().getSimpleName());

System.out.println(Integer.valueOf(testMe).toString());

System.out.println(Integer.valueOf(testMe).toString().getClass().getSimpleName());


Result:
Integer
10
String

Explanation:

  • We can use the Integer.valueOf method to acquire the Integer instance of the specified int value.
  • After receiving an instance via Integer.valueOf method we can access an object inbuilt method like getClass(), getSimpleName() and toString() to get the desired Class simple name and string version of Integer object.

When objects are created, they are pointed�by references in the stack. So, in order to access an object’s inbuilt method, it should be dereferenced. When we try to manipulate non-reference objects data, we receive a NullPointerException, which causes the program to exit/crashes.

Consider the following scenario:

public class Professor {

    public static void main(String[] args) {

        Professor obj = new Professor();

        System.out.println("Before setting obj null: " + System.identityHashCode(obj));

        System.out.println("Class name: " + obj.getClass().getSimpleName());

        obj = null; // Removing reference 

        System.out.println("After setting obj null: " + System.identityHashCode(obj));

        System.out.println("Class name: " + obj.getClass().getSimpleName());

    }
}


Result:

Before setting obj null: 1304836502

Class name: Professor

After setting obj null: 0

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Object.getClass()" because "obj" is null

Explanation:

  • Created class Professor for demonstration purpose
  • Using the System.identityHashCode method to check for Hash Code before and after setting null reference.
  • We can see that there is a valid reference to object obj in the result, and we can print the associated class name as Professor.

Once we’ve set a reference to null .�This indicates that the object no longer has a valid reference pointing to it.

As a result, if we try to use the object member method on a null reference, it will complain since it is attempting to dereference, which is not possible with primitive and null references.

As shown above, a NullPointerException will be thrown.

It’s possible that the reason for dereferenced is the same. Consider the following scenario:

 int var = 10;
if (var.equals(10) ) {
}
Result: dereferenced error

Explanation:

  • We’re trying to use primitive type variables (var) to access an Integer class method equals to compare two int values.
  • Primitive types, as we learned at the beginning of this post, do not contain any member methods for manipulating values, such as equals, toString, and so on. As a result, a dereferenced error occurs.

Let’s look at how equals can be used to compare int numbers.

int var = 101;

Integer test = 10;

if (Integer.valueOf(var).equals(test) ) {
  System.out.println("Given number is equal to 10");
} else {
  System.out.println("Given number is not equal to 10");
}

Result: Given number is not equal to 10

Integer.valueOf returns an integer representation of an int value, which can then be compared using the equals method.

Yes, it was beneficial.

Yes, it was helpful, however more information is required.

It wasn’t helpful, so no.

Feedback (optional) Please provide additional details about the selection you chose above so that we can analyze the insightful comments and ideas and take the necessary steps for this topic. Thank you

Send Feedback

In this post, I will be sharing how to solve int cannot be dereferenced in java. If you are familiar with java, then you might know that there are two datatypes in java:
a. Primitive data type
b. Non-primitive data type

Primitive data types are int, char, float, double, boolean, byte, and short.


Read Also:
java.lang.ClassNotFoundException with Example

Non-primitive data types are String, Arrays, Integer, Character etc. They are also called reference types because they refer to objects.

This error is mostly faced by java beginners and one of the most common reason is calling a method on primitive data type. Since int is primitive, it can not be dereferenced.

We will understand the error with the help of some examples. First we will produce the error before moving onto the solution.


Example 1: Producing the error by calling equals() method

If we call equals() method on primitive type int instead of ==(equality operator) to check equality.

public class JavaHungry {
    public static void main(String args[]) {
    int var = 100;

if(var.equals(100))

{ System.out.println(var); } } }

Output:
/JavaHungry.java:4: error: int cannot be dereferenced
if(var.equals(100))
^
1 error

Solution:

The above compilation error can be resolved by replacing equals() method with == equality operator.

public class JavaHungry {
    public static void main(String args[]) {
    int var = 100;

if(var == 100)

{ System.out.println(var); } } }

Output:
100


Example 2: Producing the error by calling toString() method

If we want to convert each element of the given int array to String using toString() method then we will get the int cannot be dereferenced error in java.

public class JavaHungry {
    public static void main(String args[]) {
    int[] arr = {20, 56, 70, 89};
    String output = null;
    for( int i=0; i< arr.length; i++)
        {

output = arr[i].toString();

System.out.print(output+" "); } } }

Output:
/JavaHungry.java:7: error: int cannot be dereferenced
output = arr[i].toString();
^
1 error

Solution:

The above compilation error can be resolved by three ways:

1. By casting int to Integer before calling toString() method
2. By using Integer.toString() method
3. By changing the int[] to Integer[]

1. Casting int to Integer before calling toString() method

public class JavaHungry {
    public static void main(String args[]) {
    int[] arr = {20, 56, 70, 89};
    String output = null;
    for( int i=0; i< arr.length; i++)
        {

output = ((Integer)arr[i]).toString();

System.out.print(output+" "); } } }

Output:
20 56 70 89

2. Using Integer.toString() method

public class JavaHungry {
    public static void main(String args[]) {
    int[] arr = {20, 56, 70, 89};
    String output = null;
    for( int i=0; i< arr.length; i++)
        {

output = Integer.toString(arr[i]);

System.out.print(output+" "); } } }

Output:
20 56 70 89

3. Changing the int[] to Integer[]

public class JavaHungry {
    public static void main(String args[]) {

Integer[] arr = {20, 56, 70, 89};

String output = null; for( int i=0; i< arr.length; i++) { output = arr[i].toString(); System.out.print(output+" "); } } }

Output:
20 56 70 89

That’s all for today, please mention in comments in case you have any questions related to int can not be dereferenced in java.

1. Overview

In this tutorial, we’ll take a closer look at the Java error, “int cannot be dereferenced”. First, we’ll create an example of how to produce it. Next, we’ll explain the leading cause of the exception. And finally, we’ll see how to fix it.

2. Practical Example

Now, let’s see an example that generates a compilation error, “X cannot be dereferenced”.

Here, X represents one of the eight Java primitives, namely intbyteshortlongfloatdoubleboolean, and char.

First, let’s create a class Test and compare an int to some other value:

int x = 10;
System.out.println(x.equals(10));

When compiling the code from the terminal, we’ll get the error:

$ javac Test.java
Test.java:8: error: int cannot be dereferenced
        System.out.println(x.toString());
                            ^
1 error

Also, modern IDEs like Eclipse and IntelliJ will show an error without even compiling:

EclipseIDEError

3. Cause

In Java, a reference is an address to some object/variable. Dereferencing means the action of accessing an object’s features through a reference. Performing any dereferencing on a primitive will result in the error “X cannot be dereferenced”, where X is a primitive type. The reason for this is that primitives are not considered objects — they represent raw values:

int x = 10;
System.out.println(x.equals(10));

When building the code from the terminal, we’ll get the error “int cannot be dereferenced”.

However, with Object, it works fine:

Object testObj = new Object();
testObj.toString();

Here, testObj is an object, and dereferencing happens on calling toString() with the . operator on testObj. This will not give any error as testObj is an object and, thus, dereferencing will work.

4. Solution

In our example, we need to check the equality of the two values.

The first solution to our problem is to use == instead of equals() for primitive types:

int x = 10;
System.out.println(x == 10);

When we run the code, it will print “true”.

The second solution is to change the primitive to a wrapper class.

Java provides wrapper class objects for each primitive type.

For instance, we can convert primitive types to a wrapper object if we must use equals():

Integer x = 10;
System.out.println(x.equals(10));

This error does not have a one-size-fits-all solution. Depending on the use case, we may use either of the above two solutions.

5. Conclusion

We’ve explained Java’s “int cannot be dereferenced” error. Then, we discussed how to produce the error and the cause of the exception. Lastly, we discussed a solution to resolve the error.

Понравилась статья? Поделить с друзьями:
  • Error insufficient privileges to write to macports install prefix
  • Error insufficient permission for adding an object to repository database git objects
  • Error insufficient pci resources detected как исправить
  • Error insufficient memory как исправить принтер
  • Error insufficient memory reserved for statement