Pointers in Miranda
public class Pointers {
// We'll show how references work in contrast to values with
// 2 methods: `zeroval` and `zeroref`. `zeroval` has an
// `int` parameter, so arguments will be passed to it by
// value. `zeroval` will get a copy of `ival` distinct
// from the one in the calling method.
public static void zeroval(int ival) {
ival = 0;
}
// `zeroref` in contrast has an `Integer` parameter, which is an object
// reference in Java. Modifying the object will affect the original
// reference.
public static void zeroref(Integer iref) {
iref = 0;
}
public static void main(String[] args) {
int i = 1;
System.out.println("initial: " + i);
zeroval(i);
System.out.println("zeroval: " + i);
// In Java, we use Integer wrapper class to simulate pointer-like behavior
Integer iWrapper = new Integer(i);
zeroref(iWrapper);
i = iWrapper; // Unbox the Integer back to int
System.out.println("zeroref: " + i);
// Java doesn't have direct pointer manipulation, but we can print object identities
System.out.println("object identity: " + System.identityHashCode(iWrapper));
}
}
Java doesn’t have pointers in the same way as some other languages, but it does use references for objects. In this example, we’ve adapted the concept to show how Java handles value types (primitives) and reference types (objects).
zeroval
doesn’t change the i
in main
, but zeroref
does because it has a reference to the Integer
object.
To run the program, compile it and then use java
:
$ javac Pointers.java
$ java Pointers
initial: 1
zeroval: 1
zeroref: 0
object identity: 366712642
Note that the zeroval
method doesn’t affect the original value, while zeroref
does change it. The last line prints the object’s identity hash code, which is somewhat analogous to a memory address in languages with explicit pointers.
In Java, primitives are passed by value, while objects are passed by reference. The Integer
class is used here to wrap the int
primitive, allowing us to simulate pointer-like behavior.