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