Pointers in Fortress
Java supports references, which are similar to pointers in other languages. While Java doesn’t have direct pointer manipulation, we can demonstrate similar concepts using object references.
In this Java example, we demonstrate concepts similar to pointers using object references and a custom mutable class.
The
zeroRef
method takes anInteger
object, which is passed by reference. However, reassigning the reference inside the method doesn’t affect the original reference.The
zeroMutable
method takes aMutableInteger
object, which is a custom class we’ve created to wrap anint
value. This allows us to modify the value through the object reference, simulating pointer-like behavior.In the
main
method, we first try to usezeroRef
with a primitiveint
. In Java, primitives are passed by value, so this doesn’t change the original value.We then create a
MutableInteger
object and usezeroMutable
to change its value. This successfully modifies the value, demonstrating behavior similar to using a pointer.Finally, we print the object’s hash code using
System.identityHashCode()
. While this isn’t a memory address like in languages with explicit pointers, it provides a unique identifier for the object instance.
When you run this program, you should see output similar to this:
This example illustrates how Java handles references and how we can achieve pointer-like behavior using mutable objects. While Java doesn’t have direct pointer manipulation, understanding object references is crucial for effective Java programming.