Pointers in CLIPS

Java doesn’t have pointers in the same way Go does, but we can demonstrate similar concepts using object references and primitive wrapper classes.

Our example will show how object references work in contrast to primitive values with two methods: changeValue and changeReference. changeValue has an Integer parameter, so arguments will be passed to it by value. changeValue will get a copy of the Integer object distinct from the one in the calling method.

public class PointersExample {
    static void changeValue(Integer val) {
        val = 0;
    }

    static void changeReference(Integer[] ref) {
        ref[0] = 0;
    }

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

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

        Integer[] iRef = {i};
        changeReference(iRef);
        System.out.println("changeReference: " + iRef[0]);

        System.out.println("object reference: " + System.identityHashCode(i));
    }
}

changeReference in contrast has an Integer[] parameter, which is effectively a reference to an array containing an Integer. Assigning a value to the first element of this array changes the value that the reference points to.

The System.identityHashCode() method is used to print a unique identifier for the object, which is analogous to printing the memory address in languages with explicit pointer support.

When we run this program, we’ll see:

$ javac PointersExample.java
$ java PointersExample
initial: 1
changeValue: 1
changeReference: 0
object reference: 1956725890

changeValue doesn’t change the i in main, but changeReference does because it has a reference to the array containing the Integer object.

This example demonstrates that in Java:

  1. Primitive wrapper objects like Integer are immutable, so changeValue doesn’t affect the original value.
  2. Arrays are passed by reference, so changeReference can modify the contents of the array.
  3. We can use object references to achieve behavior similar to pointers in other languages.

While Java doesn’t have explicit pointer arithmetic or dereferencing, understanding object references is crucial for effective Java programming.