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
public class test {
public static void main(String[] args) {
int x = 5;
System.out.println(x.length);
}
}
output
test.java:5: error: int cannot be dereferenced
System.out.println(x.length);
1 error
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 .
Related Topics
- Reached end of file while parsing
- Unreachable statement error in Java
- How to fix java.lang.classcastexception
- How to fix java.util.NoSuchElementException
- How to fix "illegal start of expression" error
- How to resolve java.net.SocketException: Connection reset
- Non-static variable cannot be referenced from a static context
- Error: Could not find or load main class in Java
- How to Handle OutOfMemoryError in Java
- How to resolve java.net.SocketTimeoutException
- How to handle the ArithmeticException in Java?