Pointers in Java
Java doesn’t have direct pointer manipulation like Go, but it does have reference types. We’ll demonstrate this concept using objects instead of primitive types.
public class Pointers {
static class IntegerWrapper {
int value;
IntegerWrapper(int value) {
this.value = value;
}
}
// This method receives a copy of the object reference
static void zeroValue(IntegerWrapper obj) {
obj = new IntegerWrapper(0);
}
// This method receives the object reference and can modify the original object
static void zeroReference(IntegerWrapper obj) {
obj.value = 0;
}
public static void main(String[] args) {
IntegerWrapper i = new IntegerWrapper(1);
System.out.println("initial: " + i.value);
zeroValue(i);
System.out.println("zeroValue: " + i.value);
zeroReference(i);
System.out.println("zeroReference: " + i.value);
// In Java, we can't print memory addresses directly,
// but we can print the object's hash code
System.out.println("object hash: " + System.identityHashCode(i));
}
}
In this Java example, we use an IntegerWrapper
class to demonstrate the concept of references, which is similar to pointers in Go.
The zeroValue
method receives a copy of the object reference. Assigning a new object to this reference doesn’t affect the original object in the calling method.
The zeroReference
method also receives a copy of the object reference, but it modifies the object that the reference points to, which affects the original object.
In the main
method, we create an IntegerWrapper
object and demonstrate how these methods affect (or don’t affect) the original object.
Here’s what you’d see when running this program:
$ javac Pointers.java
$ java Pointers
initial: 1
zeroValue: 1
zeroReference: 0
object hash: 1234567890
Note that zeroValue
doesn’t change the i
in main
, but zeroReference
does because it modifies the object that i
refers to.
In Java, we can’t directly print memory addresses like in Go. Instead, we’ve used System.identityHashCode()
to print a unique identifier for the object, which serves a similar purpose in this context.
This example demonstrates how Java handles objects by reference, which is conceptually similar to how Go uses pointers, albeit with some important differences in terms of direct memory manipulation.