Pointers in Logo

Java does not have direct pointer manipulation like Go, but it does have reference types which can be used to achieve similar behavior. We’ll demonstrate this using object references and a mutable integer wrapper class.

class IntWrapper {
    public int value;

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

public class PointersExample {
    // This method demonstrates pass-by-value behavior
    public static void zeroValue(int value) {
        value = 0;
    }

    // This method demonstrates pass-by-reference behavior
    public static void zeroReference(IntWrapper ref) {
        ref.value = 0;
    }

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

        zeroValue(i);
        System.out.println("zeroValue: " + i);

        IntWrapper wrapper = new IntWrapper(i);
        zeroReference(wrapper);
        System.out.println("zeroReference: " + wrapper.value);

        // In Java, we can't print memory addresses directly,
        // but we can print the object's hash code
        System.out.println("object hashcode: " + wrapper.hashCode());
    }
}

In this example, we show how Java handles value types and reference types differently:

  1. The zeroValue method takes an int parameter, which is a primitive type in Java. When we pass i to this method, Java creates a copy of the value. Changes to this copy inside the method do not affect the original variable in the main method.

  2. The zeroReference method takes an IntWrapper parameter, which is a reference type. When we pass wrapper to this method, Java passes a reference to the object. Changes made to the object through this reference inside the method affect the original object.

  3. In the main method, we create an int variable and an IntWrapper object to demonstrate these differences.

  4. We can’t directly print memory addresses in Java like we can in Go. Instead, we print the object’s hash code, which is a unique integer value for the object (although not guaranteed to be unique, it’s often used for similar purposes).

When you run this program, you should see output similar to this:

initial: 1
zeroValue: 1
zeroReference: 0
object hashcode: 1234567  // The actual number will vary

This output demonstrates that:

  1. zeroValue doesn’t change the original i in main.
  2. zeroReference does change the value in the IntWrapper object.
  3. We can print a representation of the object’s identity using its hash code.

While Java doesn’t have explicit pointers like Go, understanding the difference between value types (primitives) and reference types (objects) is crucial for Java developers, as it affects how data is passed between methods and how it can be modified.