"error: int cannot be deferenced"

"error: int cannot be deferenced"

Understanding the Java error "int cannot be dereferenced"

src/main/java/Kata.java:4: error: int cannot be dereferenced
    String str = num.toString();
                    ^
1 error

Yesterday, whilst completing a Java kata on Codewars, I came across an error that I had not seen before and did not understand - "int cannot be deferenced". Here's what I discovered....

You can't call toString() on a primitive in Java

To solve the kata, which asked you to convert a number to a string, I had tried to call the toString() method on an int variable holding the number to be converted.

class Kata {
  public static String numberToString(int num) {
    // Return a string of the number here!
    String str = num.toString();
    return str;
  }
}

// This code results in the following error: 

src/main/java/Kata.java:4: error: int cannot be dereferenced
    String str = num.toString();
                    ^
1 error

Turns out you can't call the toString() method on an int, nor on any other kind of primitive (i.e. byte, char, double, float, boolean, short, long).

Why not? Well the toString() method is only a thing for objects, not primitives.

Primitives are, well, primitive, so they don't have things like methods - they represent raw values and are stored directly on the stack.

Primitives vs Objects in Java

It comes down to the two different variable types in Java - primitives and objects. Only objects are reference types. What does reference types mean? Well, whereas primitives are just raw values stored directly on the stack, objects are given a dedicated place in memory (on the heap) and as such, the variable actually stores an address/pointer or reference that points to the place where the object is stored in memory. The process of accessing that value by using its address/pointer/reference is called dereferencing.

Since a variable of type int is a primitive type, it does not therefore hold a reference and so, of course, cannot be deferenced.

So when I tried to call the toString() method on a primitive int variable, the computer's thought process went something like this... 'OK, she has called the toString() method on a variable called num. That means num must be an object because it's got a method, so I'll use the reference that must be stored in this num variable, go and access the object itself (i.e. I'll dereference it), and I'll be able to access its toString() method...oh but wait...num doesn't hold a reference at all, it's just a primitive int! I can't dereference it! Throw an error! error: int cannot be dereferenced

So in a nutshell, that's why you can't call toString() on an int.