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.

public class Pointers {

    // This method takes an Integer object, which is passed by reference
    static void zeroRef(Integer iRef) {
        iRef = 0;
    }

    // This method takes a custom mutable object
    static void zeroMutable(MutableInteger mInt) {
        mInt.setValue(0);
    }

    public static void main(String[] args) {
        int i = 1;
        System.out.println("initial: " + i);

        // In Java, primitive types are passed by value
        zeroRef(i);
        System.out.println("zeroRef: " + i);

        // Using a mutable object to simulate pointer behavior
        MutableInteger mi = new MutableInteger(i);
        zeroMutable(mi);
        System.out.println("zeroMutable: " + mi.getValue());

        // Java doesn't allow direct access to memory addresses,
        // but we can print the object's hash code
        System.out.println("hashCode: " + System.identityHashCode(mi));
    }
}

// A mutable wrapper for int to simulate pointer-like behavior
class MutableInteger {
    private int value;

    public MutableInteger(int value) {
        this.value = value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }
}

In this Java example, we demonstrate concepts similar to pointers using object references and a custom mutable class.

  1. The zeroRef method takes an Integer object, which is passed by reference. However, reassigning the reference inside the method doesn’t affect the original reference.

  2. The zeroMutable method takes a MutableInteger object, which is a custom class we’ve created to wrap an int value. This allows us to modify the value through the object reference, simulating pointer-like behavior.

  3. In the main method, we first try to use zeroRef with a primitive int. In Java, primitives are passed by value, so this doesn’t change the original value.

  4. We then create a MutableInteger object and use zeroMutable to change its value. This successfully modifies the value, demonstrating behavior similar to using a pointer.

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

initial: 1
zeroRef: 1
zeroMutable: 0
hashCode: 1234567890

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.