Pointers and references
Unlike some other programming languages like C++, Java does not have explicit pointers. Instead, it uses references to objects in memory. Here's an overview of pointers and references in Java
Understanding pointers and references
A pointer is a variable that stores the memory address of another variable. Pointers can be used to directly manipulate memory, which can be very powerful but also dangerous if not used carefully.
In Java, we don't have direct access to memory addresses like in C++. Instead, we use references to objects in memory. A reference is a variable that stores the address of an object in memory, but we don't have direct access to the memory address itself.
Declaring and using pointers
To declare a reference in Java, we use the object type followed by a variable name, like this:
This declares a reference variable named objRef
that can refer to objects of the type MyObject
.
To assign an object to the reference variable, we use the new
keyword to allocate memory for the object and return a reference to it:
Now obj
refers to a newly-allocated object of type MyObject
.
Pointer arithmetic
Pointer arithmetic is the ability to perform arithmetic operations on pointers to move them to different memory locations. Java does not support pointer arithmetic, since it does not allow direct manipulation of memory.
Memory allocation and deallocation
Java manages memory allocation and deallocation automatically through a process called garbage collection. When an object is no longer being used by a program, the garbage collector automatically frees up the memory used by that object.
That covers the basics of pointers and references in Java!
Last updated