Pointers in Mercury
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.
static void zeroval(int ival) {
ival = 0;
}
// `zeroref` in contrast has an `Integer` parameter, which is an object
// reference in Java. When we modify the value of the Integer object,
// it affects the original reference.
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);
// We create an Integer object to demonstrate reference behavior
Integer iRef = new Integer(i);
zeroref(iRef);
System.out.println("zeroref: " + iRef);
// In Java, we can't directly print memory addresses,
// but we can print the hashcode of the object
System.out.println("hashcode: " + System.identityHashCode(iRef));
}
}
Java doesn’t have pointers in the same way that some other languages do. Instead, it uses references for objects. Primitive types (like int
) are passed by value, while objects are passed by reference.
In this example, we’ve adapted the concept to show the difference between passing primitive types by value and objects by reference:
The
zeroval
method takes anint
parameter, which is passed by value. Changes to this parameter inside the method don’t affect the original variable.The
zeroref
method takes anInteger
object as a parameter.Integer
is a wrapper class forint
, and it’s passed by reference. Changes to this object inside the method affect the original reference.In the
main
method, we demonstrate both behaviors:- Calling
zeroval
doesn’t change the originali
variable. - Calling
zeroref
changes the value of theiRef
object.
- Calling
Instead of printing the memory address (which isn’t directly accessible in Java), we print the object’s hash code, which serves as a unique identifier for the object.
When you run this program, you’ll see output similar to this:
initial: 1
zeroval: 1
zeroref: 0
hashcode: 1829164700
This shows that zeroval
didn’t change the original value, but zeroref
did change the value of the Integer
object. The hashcode provides a way to identify the object, similar to how a memory address would in languages with explicit pointers.