Int cannot be dereferenced java ошибка

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.6k12 gold badges98 silver badges136 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

342k22 gold badges227 silver badges363 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.7k4 gold badges49 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

81.2k22 gold badges142 silver badges265 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,0983 gold badges33 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.

Last Updated :
10 Jan, 2022

Like Article

Save Article

I am beginning to program War (the card game) and the methods have already been instantiated I need to know why I keep getting these errors.

import java.util.*;

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

        CardDeck CardDeckA = new CardDeck();
        //creates a standard card deck with 52 cards 1 - 10, J, Q, K, A diamond, spade, club, heart


        //Card( int value, int suit)

        int[] player1 = new int[52];
        int[] player2 = new int[52];
        int a = player1.length;
        int b = player2.length;

        for (int i = 0; a <= 26; i++) {
            player1[i].deal(); //Error: int cannot be dereferenced
            //deal( int n):Deals n cards from the top of the CardDeck, returns Card[]
        }

        for (int j = 0; a <= 26; j++) {
            player2[j].deal();//Error: int cannot be dereferenced
        }
    }
}

asked May 23, 2013 at 0:55

IAmBadAtThis's user avatar

4

You should call the method as something like

player = CardDeckA.deal(1)

instead of

player1[i].deal()

since player1[i] is a primitive int, it does not have methods.

deal returns int[], depending on how you use it, I suspect it would something similar to:

player = CardDeckA.deal(26)

answered May 23, 2013 at 0:56

zw324's user avatar

zw324zw324

26.7k16 gold badges85 silver badges117 bronze badges

3

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.

The int cannot be dereferenced to string, and the system displays an error log when calling a primitive datatype equals method using broken values and properties. For instance, any program or operating system does not consider primitive objects because they represent raw values, so calling them datatype int terminates the application and displays the dereferenced” error.Int Cannot Be Dereferenced

Nevertheless, the system can raise int cannot be dereferenced compareto warnings, although most elements and code snippets are fully functional. As a result, we compiled a profound debugging guide to teach you how to fix int cannot be dereferenced exception using real-life examples and without affecting other elements and inputs, which is critical when working on complex projects.

Contents

  • Why Is the Int That Cannot Be Dereferenced Mistake Happening?
    • – Using Blue J in Java To Compile Catalogs
    • – Dereferencing a Primitive Using Invalid Procedures
  • How To Fix the Int That Cannot Be Dereferenced Code Exception?
    • – Casting the Int to an Integer Before Calling the Method
  • Conclusion

Why Is the Int That Cannot Be Dereferenced Mistake Happening?

The int cannot be dereferenced tostring Java exception is happening because you are trying to call a primitive datatype int using invalid inputs. For instance, all programs and operating systems do not consider primitive objects because they represent raw values, so calling them datatypes blocks the syntax.

So, calling the primitives incorrectly and launching their datatype int values to run standard procedures is this error’s top culprit. Although this procedure sounds straightforward because primitives require primary inputs and properties, your application can fail to recognize and render the elements.

This int cannot be dereferenced length flaw causes unexpected errors and obstacles, including the dereferenced int code exception, which can affect other primary or secondary processes. Therefore, reproducing the error log is as important as applying the debugging procedures, especially if you want to avoid further complications and obstacles.

On the contrary, your system likely experiences the double cannot be dereferenced Java message when launching objects that are not reference types. For example, all Java dereferencing procedures contain two variables designed for specific purposes and must never be mistaken when calling the primitive datatypes int properties.

In addition, we suggest not referencing the heap memory using the raw values because char cannot be dereferenced, although this process does not guarantee the error to disappear. Therefore, let us reproduce and recreate the broken exception using real-life examples and scripts before implementing the solutions and teaching the most sophisticated debugging techniques.

– Using Blue J in Java To Compile Catalogs

We confirmed this broken exception using Blue J in Java to compile catalogs with simple voids. However, the system displays an error log and terminates the problem because the script has a primitive-type id but not an object, and the long cannot be dereferenced, confusing the output and halting all processes.Int Cannot Be Dereferenced Causes

This malfunction occurs in the leading dependencies, confirming the lack of adequate properties. We will exemplify this code snippet and the elements.

You can learn more about the invalid syntax in the following example:

public class Catalog {

private Item[] list;

private int size;

// This constructs an empty catalog with the specified capacity.

public Catalog (int max) {

list = new Item [max];

size = 1;

}

// This inserts a new item into the catalog.

// This throws 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;

}

// Locate the catalog for the item whose item number

// is the parameter id. Return the adequate object

// if the search succeeds. Display an ItemNotFound

// exception if the search breaks.

public Item find (int id) throws ItemNotFound {

for (int pos = 1; pos < size; ++pos){

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

return list [pos];

}

else {

throw new ItemNotFound();

}

}

}

}

As you can tell, the example has several comments to help you understand each element’s purpose and function. However, other instances of confusing your program and displaying the error log exists.

– Dereferencing a Primitive Using Invalid Procedures

This article’s introductory chapter confirmed the error log is inevitable when dereferencing a primitive using invalid procedures and elements. For example, your system malfunctions and fails to render the values because you called a primitive datatype int as an object, although it does not have those properties.

As a result, we will exemplify this process with simple elements and values to confirm the mistake affects short and complex projects or applications. However, we will not provide the complete stack trace because the message differs for each system and document, although the root and debugging processes remain unchanged.

The following example provides the incorrect code snippet:

// This Java Program Illustrates the Dereference

// Importing the required classes

import java.io.*;

import java.util.*;

// This is the main class

class GFG {

// This is the main driver method

public static void main (String[] args)

{

// Reading the input from keyboard by

// creating an object of Scanner class

Scanner sc = new Scanner (System.in);

// Taking the input for two integer variables

int a = sc.nextInt();

int b = sc.nextInt();

// Calculating the sum of two variables and storing the

// value in the sum variable

int sum = a + b;

// Print and display the resultant length

System.out.println (sum.length);

}

}

So, this script fails to complete the procedures because the primitives are not objects and have no member variable methods. As a result, the system cannot launch the primitive.something() element to complete the dereference. In addition, the application returns an invalid syntax in Java, although the other operations are fully functional.

How To Fix the Int That Cannot Be Dereferenced Code Exception?

You can fix the int that cannot be dereferenced code exception by changing the int array to an integer to complete the dereferenced process. In addition to that, you can use the get class or get simple name values to obtain the necessary class and integer object.



So, although the code exception has several culprits and responsible elements, the debugging techniques fix all documents regardless of purpose. We will exemplify how to change the int array to an integer by listing the invalid and corrected syntaxes to perceive the differences.

The following example introduces the invalid code snippet:

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: 1636278

Class name: Professor

After setting obj null: 0

Exception in thread “main” java.lang.NullPointerException: Cannot invoke “Object.getClass()”

because “obj” is null

Although most elements and tags appear fully functional, the system fails the procedure.

So, learn how to change the int array and overcome the broken message using the following code snippet:

int testMe = 11;

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

11

String

The fixed syntax confirms repairing your document and removing the invalid code line only takes a minute and does not compromise other elements. Still, we suggest isolating the incorrect syntax before altering the code.

– Casting the Int to an Integer Before Calling the Method

This article’s second solution suggests casting the int to an integer before calling the method to complete the dereference. As a result, the code snippet returns a correct visual output, and the system does not display warnings or error logs. But again, we will exemplify this process by providing and comparing the incorrect and repaired code snippets.Casting the Int to an Integer Before Calling the Method

The following example fails to complete the procedure:

public class JavaHungry {

public static void main (String args[]) {

int[] arr = {22, 58, 71, 89};

String output = null;

For ( int I = 0; I < arr.length; I + +)

{

output = arr [i] .toString();

System.out.print (output + ” “);

}

}

}

As you can tell, we omitted the incorrect message because it is irrelevant when casting the int to an integer before calling the method. In addition, you can implement this approach to all documents regardless of elements and purpose.

You can learn more about the corrected code snippet in the following example:

public class JavaHungry {

public static void main (String args[]) {

int[] arr = {22, 58, 71, 89};

String output = null;

For ( int I = 0; I < arr.length; I + +)

{

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

System.out.print (output + ” “);

}

}

}

This example completes our debugging journey that removes mistakes and does not affect other processes.

Conclusion

The int that cannot be dereferenced, and the application displays an error log when calling a primitive datatype int using broken values. Still, we fixed the issues, so let us remember the critical points:

  • All operating systems do not consider primitives as objects because they represent raw values
  • Reproduce the error by using Blue J in Java to compile catalogs with simple voids
  • Changing the int array to an integer is this article’s first debugging procedure
  • You can repair the mistake by casting the int to an integer before calling the method

The error will no longer obliterate your programming experience or application after using these methods. In addition, the solutions fix all documents regardless of purpose.

  • Author
  • Recent Posts

Position is Everything

Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team

Position is Everything

Понравилась статья? Поделить с друзьями:
  • Insurgency sandstorm ошибка при запуске
  • Insufficient output amount pancake ошибка
  • Insufficient memory ошибка принтера hp laserjet 2015
  • Insufficient funds for gas price value ошибка
  • Insufficient free disk space ошибка